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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With