无字符串顺序的模式匹配

问题描述 投票:0回答:2

我想匹配两个字符串,但顺序并不重要。例如,下面的检查应该给出 true 而不是 false。

final String line = "LIST \"\" (\"car1\" \"car0\") RETURN (SPECIAL-USE STATUS)\n";
final String regex = ".*LIST.*\\(\"car0\"\\ \"car1\"\\)\\ RETURN.*\\R";
System.out.println(line.matches(regex));

我期望字符串行中的值应与正则表达式匹配,而不管单词的顺序(car1 和 car0)。

java pattern-matching string-matching
2个回答
0
投票

正则表达式变量可以写成:

final String regex = ".*LIST.*\\(\"car[1|0]\"\\ \"car[1|0]\"\\)\\ RETURN.*\\R";

0
投票

你可以这样做。

final String regex = ".*LIST.*\\((?:\"car1\" \"car0\"|\"car0\" \"car1\")\\) RETURN.*\\R";

如果您不明白它的含义,您应该熟悉

java.util.regex.Pattern
的文档。当涉及到用 Java 编写正则表达式时,该链接基本上就是您的圣经。

如果这对您来说还不够清楚,这里是完全相同的字符串的分解图,但详细说明了每个单独组件的含义。

final String regex = ""
    + ".*"     //wildcard -- anything or nothing can go here.
    + "LIST"   //the literal string LIST in all-caps
    + ".*"     //another wildcard
    + "\\("    //an escaped opening parentheses
    + "(?:"    //the opener of a non-capturing capture group
    + "\""     //an escaped double quote
    + "car1"   //the literal string car1
    + "\""     //another escaped double quote
    + " "      //a single whitespace -- pressing the space bar once
    + "\""     //yet another escaped double quote
    + "car0"   //the literal string car0
    + "\""     //4th double quote thus far
    + "|"      //This is a very special symbol -- when you place this symbol
               //inside of any type of capture group, you should treat it
               //like an or operator in Java if statements
    + "\""     //5th double quote thus far
    + "car0"   //the literal string car0
    + "\""     //6th double quote thus far
    + " "      //another whitespace
    + "\""     //7th double quote thus far
    + "car1"   //the literal string car1
    + "\""     //8th double quote thus far -- it is also the last one
    + ")"      //the closer of the non-capturing capture group started above
    + "\\)"    //an escaped closing parentheses
    + " "      //yet another whitespace
    + "RETURN" //the literal string RETURN in all-caps
    + ".*"     //yet another wildcard
    + "\\R"    //This is a linebreak matcher -- it matches all new line symbols
    ;

一些注意事项。

  1. 转义意味着你决定不再解释一个符号的特殊含义,而你只想让 Java 将它放入 String 中。要转义,可以使用反斜杠符号 (\)。正如您所看到的,逃脱可能会变得很棘手。有时您需要 2 个反斜杠,有时您需要 1 个。如果您需要帮助了解何时何地需要 1 个或 2 个(或更糟糕的是,更多),我会看一下此链接。

Java 正则表达式 - 如何使用反斜杠

  1. 一个捕获组加上一个 |符号允许您在正则表达式中执行 OR 子句。上面的正则表达式基本上是说,“匹配一个通配符,后跟 LIST,后跟另一个通配符,后跟左括号,后跟 OR CLAUSE,其中以下情况之一必须为真。要么我们匹配文字字符串 "car1" "car0" 或其他文字字符串 "car0" "car1"。在 OR CLAUSE 之后,我们匹配一个右括号、一个空格、文字字符串RETURN,另一个通配符,最后是一个新的行匹配器”。这引出了我的下一点。

  2. 除了OR子句之外,这里的一切都按顺序进行。意思是,必须先匹配一个,然后才能匹配下一个。 OR CLAUSE 使您能够在其中一个选项之间进行分支,但仅此而已。否则,一切都遵循循序渐进的规则。

© www.soinside.com 2019 - 2024. All rights reserved.