我正在寻求一些有关创建正则表达式以替换以下格式的文本的帮助:
Replace the 3 words 'OR' and 'AND' and 'NOT' with '||', '&&' and '!' respectively.
But don't replace it if those 3 words appear somewhere within quotes.
例如,句子
PANDA OR THOR AND "NOTHING OR EVERYTHING" NOT THINKING
应该改为
PANDA || THOR && "NOTHING OR EVERYTHING" ! THINKING
我正在使用 Java API String.replaceAll(regex, replacement) 来替换文本。
编辑:我不想在单个“replaceAll”语句中替换它们。我会一次更换一个。但我正在寻找有关正则表达式的帮助来替换它们。
最佳答案
您无法在一个 replaceAll
中执行此操作,因为您只有一个替换项。考虑使用正则表达式来查找您想要替换的引号或部分。然后检查找到的匹配是否不是引号并将其替换为您想要的内容(您可以使用 Matcher
及其 appendReplacement
和 appendTail
方法)。
所以你的代码看起来像
Pattern p = Pattern.compile("\"[^\"]+\"|\\bAND\\b|\\bOR\\b|\\bNOT\\b");
// "quotes" AND OR NOT
Matcher m = p.matcher(text);
StringBuffer sb =new StringBuffer();
while(m.find()){
String match = m.group();
if (match.startsWith("\"")){//it is quotation, append it without changes
m.appendReplacement(sb, match);
}else if(match.equals("AND")){
m.appendReplacement(sb, "&&");
}else //...rest of your cases
}
m.appendTail(sb);
String result = sb.toString();
关于java - 如何创建与引号外的特定文本匹配的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028212/