我需要构建一个正则表达式,仅当它不是某个字符串的一部分时才找到“ 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 */
等中的转义引号。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句