I'm trying to write a regex that will identify whether a string has 2 or more consecutive commas. For example:
hello,,457
,,,,,
dog,,,elephant,,,,,
Can anyone help on what a valid regex would be?
I'm trying to write a regex that will identify whether a string has 2 or more consecutive commas. For example:
hello,,457
,,,,,
dog,,,elephant,,,,,
Can anyone help on what a valid regex would be?
String str ="hello,,,457";
Pattern pat = Pattern.compile("[,]{2,}");
Matcher matcher = pat.matcher(str);
if(matcher.find()){
System.out.println("contains 2 or more commas");
}
The below regex would matches the strings which has two or more consecutive commas,
^.*?,,+.*$
You don't need to include start and the end anchors while using the regex with matches
method.
System.out.println("dog,,,elephant,,,,,".matches(".*?,,+.*"));
Output:
true
Try:
int occurance = StringUtils.countOccurrencesOf("dog,,,elephant,,,,,", ",,");
or
int count = StringUtils.countMatches("dog,,,elephant,,,,,", ",,");
depend which library you use: Check the solution here: Java: How do I count the number of occurrences of a char in a String?