Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to count number of commas in a string

Tags:

regex

People also ask

How do you count commas in a string?

Please do as follows: Select the cell you will place the counting result, type the formula =LEN(A2)-LEN(SUBSTITUTE(A2,",","")) (A2 is the cell where you will count the commas) into it, and then drag this cell's AutoFill Handle to the range as you need.

How do I find commas in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

How do you count in regular expressions?

To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.


/^([^,]*,){21}[^,]*$/

That is:

^     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

If you're using a regex variety that supports the Possessive quantifier (e.g. Java), you can do:

^(?:[^,]*+,){21}[^,]*+$

The Possessive quantifier can be better performance than a Greedy quantifier.


Explanation:

(?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

Exactly 21 commas:

^([^,]*,){21}[^,]$

At least 21 commas:

^([^,]?,){21}.*$

Might be faster and more understandable to iterate through the string, count the number of commas found and then compare it to 21.


^(?:[^,]*)(?:,[^,]*){21}$

if exactly 21:

/^[^,]*(,[^,]*){21}$/

if at least 21:

/(,[^,]*){21}/

However, I would suggest don't use regex for such simple task. Because it's slow.