Java regex matching multiple digit sequences separated with colon

时间:2015-06-25 18:45:15

标签: java regex

I have a string that must have the given format: at least ddd:dd or ddd:dd,ddd:dd or ddd:dd,ddd:dd,ddd:dd Seeing the JavaDoc, I use this pattern: "^[\\d{3}:\\d{2}]+[,\\d{3}:\\d{2}]*$" Code: myString.matches("^[\\d{3}:\\d{2}]+[,\\d{3}:\\d{2}]{0,2}$") It does not work, but I see no mistake.

3 个答案:

答案 0 :(得分:2)

关于你的正则表达式有一点需要注意的是它在字符类([...]中存在一个关键问题,我们在其中定义了我们想要匹配或不想匹配的符号的字符或范围)而不是组( (...)我们只使用我们需要匹配的字符序列,或者使用替代字符。 Here you can see what your regex actually matches

enter image description here

我确信{3}: a single character in the list {3}: literally确实是你不想要的。

如果d代表任何数字,则需要使用类似

的内容
String pattern = "\\d{3}:\\d{2}(?:,\\d{3}:\\d{2})*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher("111:11,222:22,222:22");

while (m.find()) {
       System.out.println(m.group());   
}

请参阅IDEONE demo

以下是an example with matches

String pattern = "\\d{3}:\\d{2}(?:,\\d{3}:\\d{2})*";
System.out.println("222:22,222:22".matches(pattern));
System.out.println("111:11,222:22,222:22".matches(pattern));

答案 1 :(得分:1)

Problems with your regex you are using \d which matches a digit You are using [] which are used for defining ranges Try ^(d{3}:d{2})(,d{3}:d{2}){0,2}$

答案 2 :(得分:1)

  • [xyz] - []表示它与列出的任何一个字符相匹配,因此xyz。< / LI>
  • (xyz)是一个群组,会匹配字符x,然后是y,然后是z

你想要这个正则表达式:

"^(\\d{3}:\\d{2}($|,(?!$)))+$"
  • ^匹配字符串的开头。
  • \\d{3}:\\d{2}符合您的模式;
  • 紧接着
  • ($|,(?!$))将匹配字符串结尾$或逗号,,后面没有字符串结尾(?!$)
  • 前面两个表达式的
  • (...)+$将匹配您的一个或多个模式(如果有多个,则必须用逗号分隔),然后是字符串结尾。