我想写一个正则表达式来验证一个单引号前面是否有另一个单引号。
有效字符串:
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
它可以在一行中完成:
inputString.matches("(?:[^']|'')*+");
正则表达式只是意味着,字符串可以包含 0 个或多个
[^']
''
*+
我使用了 0 个或多个量词 ( ) 的所有格版本 ( *
)。由于解释所有格量词的含义会很长,因此我将向您推荐这里以了解它。简单地说,它是一种优化。
不需要正则表达式,只需用空.replace()
替换所有两个单引号的序列,然后测试是否仍然找到单引号;如果是,则字符串无效:
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}[^\']*)+"
对于初学者来说很容易掌握。但这不是最好的方法。当运行长时间输入时,它会死掉(陷入回溯地狱)。