繁体   English   中英

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

[英]Regex to match 2 or more commas

我正在尝试编写一个正则表达式,用于识别字符串是否包含2个或更多连续逗号。 例如:

hello,,457
,,,,,
dog,,,elephant,,,,,

任何人都可以帮助有效的正则表达式吗?

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");
}

以下正则表达式将匹配具有两个或更多连续逗号的字符串,

^.*?,,+.*$ 

DEMO

使用带有matches方法的正则表达式时,您不需要包含开始和结束锚点。

System.out.println("dog,,,elephant,,,,,".matches(".*?,,+.*"));

输出:

true

尝试:

int occurance = StringUtils.countOccurrencesOf("dog,,,elephant,,,,,", ",,");

要么

int count = StringUtils.countMatches("dog,,,elephant,,,,,", ",,");

取决于您使用的库:在此处检查解决方案: Java:如何计算String中char的出现次数?

暂无
暂无

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

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