我需要构建一个正则表达式,只有当它不是某个字符串的一部分时才会找到单词“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)
谢谢!
答案 0 :(得分:4)
它不会是防弹的,但这适用于所有测试用例:
(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\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 */
等。
答案 1 :(得分:0)
不完全确定您的完整要求是什么,但
$\s*\bint\b
也许
答案 2 :(得分:0)
假设输入是每一行,
^int\s[\$_a-bA-B\;]*$
它遵循基本的变量命名规则:)
答案 3 :(得分:0)
如果你想解析代码并搜索孤立的int word,那么这就可以了:
(^int|[\(\ \;,]int)
您可以使用它来查找int,在代码中只能以空格开头,逗号,“;”和左括号或是第一个单词。
您可以在此处尝试并对其进行增强http://www.regextester.com/
PS:这适用于所有测试用例。
答案 4 :(得分:0)
$ [^“] * \宾特\ B'/ P>
应该有效。我想不出你可以在字符“”之后使用有效的int标识符的情况。 当然,这仅适用于代码限制为每行一个语句的情况。