用于逗号分隔列表的正则表达式

时间:2018-08-13 10:19:36

标签: regex validation

我想验证一个用逗号分隔的值列表,最后一个值后面没有逗号:

应该有效:

  

altdns1.at,altdns2.de.fr,altdns3.de

应该无效:

  

altdns1.at,altdns2.de.fr,altdns3.de,

我的RegEx:

^([^,]+,)*([^,]*)$

我的想法:

  • ([^,]+,)字符串的开头:除逗号外的任何字符-一次到无限次-后跟一个逗号
  • *这零到无限制的时间
  • ([^,]*)字符串结尾:除逗号以外的任何字符-一次到无限次

Regex101显示此字符串与我的模式匹配:

  

altdns1.de.de,altdns2.de.de,altdns3.de.de,

为什么?

1 个答案:

答案 0 :(得分:2)

使用此:

^[^,]+(?:,[^,]+)*$

说明:

^           : begining of line
  [^,]+     : 1 or more not comma
  (?:       : start non capturing group
    ,       : a comma
    [^,]+   :  1 or more not comma
  )*        : end group, may appear 0 or more times
$           : end of line
相关问题