java中的正则表达式,用于匹配不包含在单引号中的字符串



我正在分析脚本中的错误字符串,并且有一个数组列表,其中包含不应该出现在代码行中的字符串。

但是,当某些字符串不完全是字符串时,它们应该通过。

示例:

列表包含";FOO";以及";BAR";

文本行:

This is foo
and this is BAR
but not 'foo'
and not 'BAR'
but also not FOO_BAR
but we want FOO%TEXT
and also bar.text

结果

This is foo
and this is BAR
but we want FOO%TEXT
and also bar.text

我试过在网上和stackoverflow上找到的视图示例,但这些示例对我不起作用,它们不会过滤引用的示例。

String pattern = ".*\"+strTables[i]+"\b.*[^(\w|')]";
Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println (strTables[i] + ": " + line);
break;
}

您需要单词前后的b(单词边界(来匹配整个单词。

然后,在模式开始时向后看(如(?<!')(表示">前面没有单引号",在模式结束时向前看(如(?!')(表示">后面没有单引号"。

把它放在一起会产生

String pattern = "(?<!')\b" + strTables[i] + "\b(?!')";

最新更新