正则表达式匹配多个模式

时间:2014-10-05 23:19:15

标签: php regex preg-replace

我有这些

name

name[one]

name[one][two]

name[one][two][three]

我希望能够像这样匹配它们:

[name]

[name, one]

[name, one, two]

[name, one, two, three]

此处my regex I've tried

/([\w]+)(?:(?:\[([\w]+)\])+)?/

我似乎无法做到正确,只能得到最后的方括号

4 个答案:

答案 0 :(得分:1)

您不能拥有动态数量的捕获;捕获的数量正好等于捕获括号对的数量((?:...)不计算)。你有两个捕获括号对,这意味着你得到两个捕获 - 不多也不少。

要处理可变数量的匹配项,请使用子匹配项(如果您的语言支持,则使用函数替换)或拆分。

您没有使用编程语言标记,因此这是我可以去的具体内容。

答案 1 :(得分:0)

您不能在正则表达式中重复组。你可以写出很多次。这适用于方括号中最多三组。如果您愿意,可以添加更多。

(\w+)\[(\w+)\](?:\[(\w+)\])?(?:\[(\w+)\])?

答案 2 :(得分:0)

这应该([\w]+)(?:\[([\w]+)\]\+)?

http://regex101.com/r/mF8pC8/3

原始正则表达式的更改 - 删除了额外的捕获并在上一次\之前添加了+

    1st Capturing group ([\w]+)
        [\w]+ match a single character present in the list below
            Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
            \w match any word character [a-zA-Z0-9_]
            (?:\[([\w]+)\]\+)? Non-capturing group
        Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
        \[ matches the character [ literally
    2nd Capturing group ([\w]+)
        [\w]+ match a single character present in the list below
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
        \w match any word character [a-zA-Z0-9_]
        \] matches the character ] literally
        \+ matches the character + literally
    g modifier: global. All matches (don't return on first match)

答案 3 :(得分:-1)

你不能拥有使用php正则表达式捕获的动态数量...

为什么不呢,写下类似:explode('[',strtr('name[one][two][three]', [']'=>'']))的东西 - 它会给你想要的结果。