Regexf或出现不超过一次的角色

时间:2013-01-25 13:32:11

标签: regex character comma

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

正确匹配:

,111111
11111,1111
11111,

匹配不正确:

1111,,11111
11,111,111

3 个答案:

答案 0 :(得分: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) «$»
-->

答案 1 :(得分: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 break”并按每行末尾的Enter键)

答案 2 :(得分: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

根据您的要求。