我正在尝试编写一个Regex表达式,可以确定字符串是否包含奇数个"
- 引号。
this question上的回答者已经完成了一些非常相似的事情,以确定一串字母是否包含某个字母的奇数。但是我无法适应我的问题。
到目前为止,我的工作并不完全正确:
String regexp = "(\\b[^\"]*\"(([^\"]*\"){2})*[^\"]*\\b)";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher("bbacac");
if(matcher.find()){
System.out.println("Found");
}
else
System.out.println("Not Found");
答案 0 :(得分:10)
正则表达式是一个相当差的解决方案。< - 我虽然你在谈论嵌套,而不是配对。
迭代字符串中的所有字符,计算"
的实例将是实现此目的的更快,更有效的方法。
int quoteCount = 0;
for(char ch : inputString.toCharArray())
{
if(ch == '"') quoteCount++;
}
boolean even = quoteCount % 2 == 0;
答案 1 :(得分:5)
如果你想要一个正则表达式,这很容易实现:
boolean oddQuotes = subjectString.matches("[^\"]*\"(?:[^\"]*\"[^\"]*\")*[^\"]*");
说明:(没有所有Java引号转义):
[^"]*" # Match any number of non-quote characters, then a quote
(?: # Now match an even number of quotes by matching:
[^"]*" # any number of non-quote characters, then a quote
[^"]*" # twice
)* # and repeat any number of times.
[^"]* # Finally, match any remaining non-quote characters
到目前为止,这可能比简单的“计算报价”解决方案慢。但我们可以做得更好:我们可以设计正则表达式来处理转义引号,i。即如果前面有奇数个反斜杠,则不要计算引号:
boolean oddQuotes = subjectString.matches("(?:\\\\.|[^\\\\\"])*\"(?:(?:\\\\.|[^\\\\\"])*\"(?:\\\\.|[^\\\\\"])*\")*(?:\\\\.|[^\\\\\"])*");
现在不可否认,这看起来很糟糕,但主要是因为Java的字符串转义规则。实际的正则表达式很简单:
(?: # Match either
\\. # an escaped character
| # or
[^\\"] # a character except backslash or quote
)* # any number of times.
" # Then match a quote.
(?: # The rest of the regex works just the same way (as above)
(?:\\.|[^\\"])*"
(?:\\.|[^\\"])*"
)*
(?:\\.|[^\\"])*
答案 2 :(得分:1)
或者,使用正则表达式,用空字符串替换除引号之外的所有内容,并检查结果的长度。
答案 3 :(得分:1)
不要使用正则表达式。只需遍历字符串中的字符并计算"
“。它会更有效率。它是一种O(n)算法。
特别是如果它很简单并使解决方案比一些模糊的正则表达式模式更容易阅读。
boolean odd = false;
for(int i=0; i<s.length(); i++) {
if(s.chartAt(i) == '\"') odd != odd;
}
答案 4 :(得分:0)
你可以使用split并检查返回数组中的元素数是偶数还是奇数来衡量该字符频率的奇数或偶数
String s = ".. what ever is in your string";
String[] parts = s.split("\"");
if(parts.size()%2){
//String has odd number of quotes
}else{
//String has even number of quotes
}
答案 5 :(得分:0)
我不得不说,手动计算"
的数量可能会更好,但如果你真的想要一个正则表达式,那么这里应该有效:
"(^(([^\"]*\"){2})*[^\"]*$)"
我只是将表达式绑定到字符串的前面和后面,并确保只有"
对,盲目地吸收它们之间的任何"
。