帮助构建一个正则表达式

Adi*_*be7 6 java regex

我需要构建一个正则表达式,只有当它不是某个字符串的一部分时才会找到单词"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)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Boh*_*ian 4

它不会是防弹的,但这适用于您的所有测试用例:

(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\bint\b(?=([^"]*|[^"]*"[^"]*"[^"]*)$)
Run Code Online (Sandbox Code Playgroud)

它会进行向后查看和向前查看,以断言没有或有两个前面/后面的引号"

下面是 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);
    }
Run Code Online (Sandbox Code Playgroud)

输出(包括正则表达式,因此您可以在没有所有这些转义的情况下阅读它\):

(?<=^([^"]*|[^"]*"[^"]*"[^"]*))\bint\b(?=([^"]*|[^"]*"[^"]*"[^"]*)$)
true: int i;
false: String example = "int i";
false: logger.i("int");
true: logger.i("int") + int.toString();
Run Code Online (Sandbox Code Playgroud)

使用正则表达式永远不会 100% 准确 - 您需要一个语言解析器。考虑字符串中的转义引号"foo\"bar"、内嵌注释/* foo " bar */等。