我需要构建一个正则表达式,仅当它不是某个字符串的一部分时才查找单词“int”。
我想查找代码中是否使用了 int。 (不在某些字符串中,仅在常规代码中)
例子:
int i; // the regex should find this one.
String example = "int i"; // the regex should ignore this line.
logger.i("int"); // the regex should ignore this line.
logger.i("int") + int.toString(); // the regex should find this one (because of the second int)
谢谢!
最佳答案
它不会是防弹的,但这适用于您所有的测试用例:
(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\bint\b(?=([^"]*|[^"]*"[^"]*"[^"]*)$)
它会向后看并向前看,以断言前面/后面没有或有两个引号 "
这是带有输出的 java 代码:
String regex = "(?<=^([^\"]*|[^\"]*\"[^\"]*\"[^\"]*))\\bint\\b(?=([^\"]*|[^\"]*\"[^\"]*\"[^\"]*)$)";
System.out.println(regex);
String[] tests = new String[] {
"int i;",
"String example = \"int i\";",
"logger.i(\"int\");",
"logger.i(\"int\") + int.toString();" };
for (String test : tests) {
System.out.println(test.matches("^.*" + regex + ".*$") + ": " + test);
}
输出(包括正则表达式,因此您可以在没有所有那些 \
转义的情况下阅读它):
(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\bint\b(?=([^"]*|[^"]*"[^"]*"[^"]*)$)
true: int i;
false: String example = "int i";
false: logger.i("int");
true: logger.i("int") + int.toString();
使用正则表达式永远不会 100% 准确 - 您需要一个语言解析器。考虑字符串 "foo\"bar"
中的转义引号、行内注释 /* foo "bar */
等
关于java - 帮助构建正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484606/