简体   繁体   English

正则表达式匹配2个或更多逗号

[英]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. 我正在尝试编写一个正则表达式,用于识别字符串是否包含2个或更多连续逗号。 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 DEMO

You don't need to include start and the end anchors while using the regex with matches method. 使用带有matches方法的正则表达式时,您不需要包含开始和结束锚点。

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? 取决于您使用的库:在此处检查解决方案: Java:如何计算String中char的出现次数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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