Php 正则表达式匹配多模式

Php 正则表达式匹配多模式,php,regex,preg-replace,Php,Regex,Preg Replace,我有这些 name name[one] name[one][two] name[one][two][three] 我希望能够像这样匹配它们: [name] [name, one] [name, one, two] [name, one, two, three] 这是: 我只是不能很好地理解它,只得到最后的方括号你不能有动态的捕获数量;捕获的数量正好等于捕获括号对的数量((?:…)不计算)。您有两个捕获括号对,这意味着您得到两个捕获-不多也不少 要处理不同数量的匹配,请使用子匹配(

我有这些

name

name[one]

name[one][two]

name[one][two][three]
我希望能够像这样匹配它们:

[name]

[name, one]

[name, one, two]

[name, one, two, three]
这是:


我只是不能很好地理解它,只得到最后的方括号

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

要处理不同数量的匹配,请使用子匹配(如果您的语言支持,则在替换为函数中)或拆分


您没有使用编程语言进行标记,因此这是我所能做到的最具体的部分。

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

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

您不能使用php regexp动态捕获数

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

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

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

    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)

您使用什么语言或程序来实现正则表达式?(例如Sed、PHP、Python、Notepad++)PHP,当我完成测试时,该网站会将其转换为PHP,尝试
([\w]+)(?:(?:\[([\w]+)\])\+)?
。在last+之前有一个\。这些组的最大数目是多少,还是以4结尾?动态捕获数是可能的,但只有在.NET中。但是您所说的仍然适用于这里,因为OP使用的是PHP。
    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)