文字が文字列に複数回出現するのを避けようとしています。この場合、一連の数字の中で 1 回だけ出現するカンマが必要です。
正しい一致:
,111111
11111,1111
11111,
不適切な一致:
1111,,11111
11,111,111
これを試して
(?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) «$»
-->
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/
(上部の「^ $一致」を確認し、各行の最後でEnterキーを押してください)
Java では、1 文字のみをチェックする必要があるため、次の方法を使用して (正規表現を使用せずに) 実行できます。
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
必要に応じて。