0

我试图避免一个字符在字符串中出现多次。在这种情况下,我需要一个逗号在一堆数字中只出现一次。

正确匹配:

,111111
11111,1111
11111,

不正确的匹配:

1111,,11111
11,111,111
4

3 回答 3

3

尝试这个

(?im)^[0-9]*,[0-9]*$

或者,更准确地说

(?im)^([0-9]*,[0-9]+|[0-9]+,[0-9]*)$

解释

<!--
(?im)^([0-9]*,[0-9]+|[0-9]+,[0-9]*)$

Match the remainder of the regex with the options: case insensitive (i); ^ and $ match at line breaks (m) «(?im)»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below and capture its match into backreference number 1 «([0-9]*,[0-9]+|[0-9]+,[0-9]*)»
   Match either the regular expression below (attempting the next alternative only if this one fails) «[0-9]*,[0-9]+»
      Match a single character in the range between “0” and “9” «[0-9]*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      Match the character “,” literally «,»
      Match a single character in the range between “0” and “9” «[0-9]+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Or match regular expression number 2 below (the entire group fails if this one fails to match) «[0-9]+,[0-9]*»
      Match a single character in the range between “0” and “9” «[0-9]+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Match the character “,” literally «,»
      Match a single character in the range between “0” and “9” «[0-9]*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
-->
于 2013-01-25T13:45:36.377 回答
1

如果您想正确包含 1111,请使用以下内容:

^[0-9]*,?[0-9]*$  

如果没有...使用:

^[0-9]*,[0-9]*$  

解释:

^ = start of string  
[0-9]* = zero numbers or multiple numbers  
,? = a comma zero or 1 time  
,(without the ? following) = a comma must be here 
$ = the end of string

检查表达式的好网站
http://regexpal.com/
(确保检查顶部的“^$ match at line breaks”并在每行末尾按 Enter)

于 2013-01-25T13:55:12.287 回答
0

在 Java 中,可以使用以下方法(不使用正则表达式)来完成,因为我们只需要检查一个字符。

private static boolean checkValidity(String str, char charToCheck) {
    int count = 0;
    char[] chars = str.toCharArray();
    for (char ch : chars) {
        if (ch == ',' && ++count > 1) {
            return false;
        }
    }

    return true;
}

按如下方式使用它:

public static void main(String args[]) {
    System.out.println(checkValidity("111,111,111", ','));
    System.out.println(checkValidity("111,,111", ','));
    System.out.println(checkValidity("111,111", ','));
}

输出将是:

false
false
true

根据您的要求。

于 2013-01-25T14:05:59.687 回答