一重引用符の前に別の一重引用符があるかどうかを検証する正規表現を書きたいと思います。
有効な文字列:
azerty''uiop
aze''rty''uiop
''azertyuiop
azerty''uiop''
azerty ''uiop''
azerty''''uiop
azerty''''uiop''''
無効な文字列:
azerty'uiop
aze'rty'uiop
'azertyuiop
azerty'uiop'
azerty 'uiop'
azerty'''uiop
正規表現は必要ありません.replace()
。2 つの一重引用符のすべてのシーケンスを何も置き換えずに使用してから、一重引用符がまだ見つかるかどうかをテストします。はいの場合、文字列は無効です。
if (input.replace("''", "").indexOf('\'') != -1)
// Not valid!
一重引用符のない文字列が有効であることも考慮したい場合は、一時変数を作成する必要があります。
public boolean isValid(final String input)
{
final String s = input.replace("''", "");
return s.equals(input) ? true : s.indexOf('\'') == -1;
}
非常に迅速な解決策が必要ですか? 次を試してください。
public static boolean isValid(String str) {
char[] chars = str.toCharArray();
int found = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == '\'') {
found++;
} else {
if (found > 0 && found % 2 != 0) {
return false;
}
found = 0;
}
}
if (found > 0 && found % 2 != 0) {
return false;
}
return true;
}
次のコードも使用できます。
str.matches("([^\']*(\'){2}[^\']*)+");
"([^\']*(\'){2}[^\']*)+"
初心者向けで分かりやすいと思います。しかし、これは最善の方法ではありません。長い入力のために実行すると、死にます (バックトラック地獄に陥ります)。