简体   繁体   中英

Regex to match 2 or more commas

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,

^.*?,,+.*$ 

DEMO

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM