查找文本中的项目,例外[正则表达式]

时间:2015-10-04 20:07:18

标签: regex

请帮助创建一个将被分配的正则表达式“|”除括号外的所有角色。

example|example (example(example))|example|example|example(example|example|example(example|example))|example

选择后应该有5个字符“|”不合时宜。我想要注意,括号内的内容应保持不变,包括“|”他们内心的性格。

1 个答案:

答案 0 :(得分:0)

考虑到你想匹配任何括号集之外的管道,嵌套集,这里是实现你想要的模式:

<强>正则表达式:

(?x)                     # Allow comments in regex (ignore whitespace)
(?:                      # Repeat *
    [^(|)]*+             #  Match every char except ( ) or |
    (                    #  1. Group 1
        \(               #    Opening paren
        (?:              #    chars inside:
            [^()]++      #     a. everything inside parens except nested parens
          |              #      or
            (?1)         #     b. nested parens (recurse group 1)
        )                #
        \)               #   Until closing paren.
    )?+                  #   (end of group 1)
)*+                      #
\K                       #  Keep text out of match
\|                       #  Match a pipe

regex101 Demo

<强>一衬垫:

(?:[^(|)]*+(\((?:[^()]++|(?1))\))?+)*+\K\|

regex101 Demo

此模式使用了一些高级功能: