我想匹配两个字符串,但顺序并不重要。例如,下面的检查应该给出 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)。
正则表达式变量可以写成:
final String regex = ".*LIST.*\\(\"car[1|0]\"\\ \"car[1|0]\"\\)\\ RETURN.*\\R";
你可以这样做。
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
;
一些注意事项。
一个捕获组加上一个 |符号允许您在正则表达式中执行 OR 子句。上面的正则表达式基本上是说,“匹配一个通配符,后跟 LIST,后跟另一个通配符,后跟左括号,后跟 OR CLAUSE,其中以下情况之一必须为真。要么我们匹配文字字符串 "car1" "car0" 或其他文字字符串 "car0" "car1"。在 OR CLAUSE 之后,我们匹配一个右括号、一个空格、文字字符串RETURN,另一个通配符,最后是一个新的行匹配器”。这引出了我的下一点。
除了OR子句之外,这里的一切都按顺序进行。意思是,必须先匹配一个,然后才能匹配下一个。 OR CLAUSE 使您能够在其中一个选项之间进行分支,但仅此而已。否则,一切都遵循循序渐进的规则。