I have such regex:
我有这样的正则表达式:
/A|B|A,B|B,A/
Which is the best way to refactor it using groups?
哪个是使用组重构它的最佳方法?
1 个解决方案
#1
2
Since you are using PCRE, you can just wrap the subpatterns you need to repeat with capturing groups, and then just recurse them with (?n)
syntax (subroutine calls):
由于您正在使用PCRE,因此您可以将需要重复的子模式包装为捕获组,然后使用(?n)语法(子例程调用)将它们递归:
(A),(B)|(?2),(?1)|(?1)|(?2)
See the regex demo
请参阅正则表达式演示
Here, (A)
captures A
into Group 1 and (B)
captures B
into Group 2, so, in order to use these subpatterns later in the pattern, just use (?1)
to match the first subpattern and (?2)
to repeat the second one.
这里,(A)将A捕获到组1中,并且(B)将B捕获到组2中,因此,为了在模式中稍后使用这些子模式,只需使用(?1)匹配第一个子模式和(?2)重复第二个。
You can also use named capture groups:
您还可以使用命名捕获组:
(?<first>A),(?<second>B)|(?&second),(?&first)|(?&first)|(?&second)
看另一个正则表达式演示
#1
2
Since you are using PCRE, you can just wrap the subpatterns you need to repeat with capturing groups, and then just recurse them with (?n)
syntax (subroutine calls):
由于您正在使用PCRE,因此您可以将需要重复的子模式包装为捕获组,然后使用(?n)语法(子例程调用)将它们递归:
(A),(B)|(?2),(?1)|(?1)|(?2)
See the regex demo
请参阅正则表达式演示
Here, (A)
captures A
into Group 1 and (B)
captures B
into Group 2, so, in order to use these subpatterns later in the pattern, just use (?1)
to match the first subpattern and (?2)
to repeat the second one.
这里,(A)将A捕获到组1中,并且(B)将B捕获到组2中,因此,为了在模式中稍后使用这些子模式,只需使用(?1)匹配第一个子模式和(?2)重复第二个。
You can also use named capture groups:
您还可以使用命名捕获组:
(?<first>A),(?<second>B)|(?&second),(?&first)|(?&first)|(?&second)
看另一个正则表达式演示