正则表达式,用于计算字符串中逗号的数量

33 regex

如何构建一个正则表达式,它将匹配包含任何字符但必须包含21个逗号的任何长度的字符串?

Gre*_*reg 91

/^([^,]*,){21}[^,]*$/
Run Code Online (Sandbox Code Playgroud)

那是:

^     Start of string
(     Start of group
[^,]* Any character except comma, zero or more times
,     A comma
){21} End and repeat the group 21 times
[^,]* Any character except comma, zero or more times again
$     End of string
Run Code Online (Sandbox Code Playgroud)

  • 非常好的解释.只需确保将其放在代码中的注释中即可. (4认同)

Pet*_*ton 11

如果您正在使用支持占有量词的正则表达式(例如Java),您可以:

^(?:[^,]*+,){21}[^,]*+$
Run Code Online (Sandbox Code Playgroud)

占有量词可以比贪心量词更好.


说明:

(?x)    # enables comments, so this whole block can be used in a regex.
^       # start of string
(?:     # start non-capturing group
[^,]*+  # as many non-commas as possible, but none required
,       # a comma
)       # end non-capturing group
{21}    # 21 of previous entity (i.e. the group)
[^,]*+  # as many non-commas as possible, but none required
$       # end of string
Run Code Online (Sandbox Code Playgroud)


Dan*_*ner 7

正好21个逗号:

^([^,]*,){21}[^,]$
Run Code Online (Sandbox Code Playgroud)

至少21个逗号:

^([^,]?,){21}.*$
Run Code Online (Sandbox Code Playgroud)


zim*_*668 7

迭代字符串可能更快,更容易理解,计算找到的逗号数量,然后将其与21进行比较.