通过以任意顺序匹配术语来查找字符串的所有排列

时间:2020-03-11 16:39:16

标签: regex

我要查找并替换以下字符串:

<tag a=“x” b=“y” c=“z”/>

但是它可以以任何顺序显示,例如

<tag c=“z” b=“y” a=“x”/>
<tag b=“y” a=“x” c=“z”/>

查找此字符串的所有实例的正则表达式是什么?

2 个答案:

答案 0 :(得分:0)

我相信您想要的正则表达式查询是:

<tag ([a-z]){1}=“([a-z]){1}” ([a-z]){1}=“([a-z]){1}” ([a-z]){1}=“([a-z]){1}”/>

让我帮助解释此查询的元素:

  1. ([a-z])将匹配a到z之间的任何字符串
  2. 添加{1}会告诉查询您要一次匹配该查询!
  3. 因此([a-z]){1}仅匹配一次a到z之间的任何字符串。

如果在此示例中使用此元素,则匹配的字符串将为:

<tag a=“x” b=“y” c=“z”/>

匹配的字符串: t,a,g,a,x,b,y,c

如果您将字符串结构添加到查询中:

tag ([a-z]){1}=“([a-z]){1}”

匹配的字符串:标记a =“ x”

希望这会有所帮助!

答案 1 :(得分:0)

这是一种方式:

^<tag +([abc])=“([xyz])“ +(?!\1)([abc])=“(?!\2)([xyz])“ +(?!\1|\3)[abc]=“(?!\2|\4)[xyz]“\/>$

Demo

^         # match beginning of line
<tag      # match '<tag'       
 +        # match 1+ spaces
([abc])   # match 'a', 'b' or 'c' in cap group 1
=“        # match '=“'
([xyz])   # match 'x', 'y' or 'z' in cap group 2
“ +       # match '“' followed by 1+ spaces 
(?!\1)    # following cannot match contents of cap group 1
([abc])   # match 'a', 'b' or 'c' in cap group 3
=“        # match '=“'
(?!\2)    # following cannot match contents of cap group 2
([xyz])   # match 'x', 'y' or 'z' in cap group 4
“ +       # match '“' followed by 1+ spaces 
(?!\1|\3) # following cannot match contents of cap group 1 or 3
[abc]=“   # match 'a', 'b' or 'c' followed by '=“'
(?!\2|\4) # do not match contents of cap group 2 or 4
[xyz]“\/> # match 'x', 'y' or 'z' followed by '“/>'
$         # match end of line