Regex: Matching against groups in different order without repeating the group

后端 未结 4 1359
遇见更好的自我
遇见更好的自我 2021-01-31 11:21

Let\'s say I have two strings like this:

XABY
XBAY

A simple regex that matches both would go like this:

X(AB|BA)Y
4条回答
  •  名媛妹妹
    2021-01-31 11:31

    You can store regex pieces in variables, and do:

    A=/* relevant regex pattern */
    B=/* other regex pattern */
    regex = X($A$B|$B$A)Y
    

    This way you only have to specify each regex once, on its own line, which should make it easier to maintain.

    Sidenote: You're trying to find permutations, which is ok since you're only looking at 2 subregexes. But if you wanted to add a third (or fourth), your regex permutations grow drastically - (abc|acb|bac|bca|cab|cba) - or worse. If you need to go down the road of permutations, there's some good discussion on that here on stackoverflow. It's for letter permutation, and the solutions use awk/bash/perl, but that at least gives you a starting point.

提交回复
热议问题