我正在尝试为java编写正则表达式以匹配以下字符串示例:
my_phrases=[phrase1, phrase2]
my_phrases=[phrase2, phrase1]
因此,序列my_phrases=
后跟任何顺序的phrase1
和phrase2
序列应该匹配。
我做了什么:
^my_phrases.?(phrase1,phrase2|phrase2,phrase1)$
它不起作用。 你能帮忙吗?
答案 0 :(得分:1)
这样的事可能......
^my_phrases=\[((phrase1, phrase2)|(phrase2, phrase1))\]$
答案 1 :(得分:1)
您的正则表达式不起作用,因为它不考虑[
和]
以及,
之后的空格。你可以尝试这样的正则表达式:
^my_phrases.*(phrase1,\s*phrase2|phrase2,\s*phrase1).*$
但是,当然,“完美”正则表达式取决于您想要匹配的内容,例如:这些[
和]
等是否实际上是可选的或强制性的。
答案 2 :(得分:1)
这是通用的:
/^(my_phrases=\[([^,]+),\s([^,]+)\])$/gm
MATCH 1
my_phrases=[phrase1, phrase2]
phrase1
phrase2
MATCH 2
my_phrases=[phrase2, phrase1]
phrase2
phrase1
这有点具体:
/^(my_phrases=\[(phrase1|phrase2),\s(phrase1|phrase2)\])$/gm
MATCH 1
my_phrases=[phrase1, phrase2]
phrase1
phrase2
MATCH 2
my_phrases=[phrase2, phrase1]
phrase2
phrase1