[英]Regex matching multiple pattern
I have these 我有这些
name
name[one]
name[one][two]
name[one][two][three]
I want to be able to match them like this: 我希望能够像这样匹配它们:
[name]
[name, one]
[name, one, two]
[name, one, two, three]
Here's my regex I've tried : 这是我尝试过的正则表达式 :
/([\w]+)(?:(?:\[([\w]+)\])+)?/
I just can't quite to seem to get it right, only gets the last square brackets 我只是似乎不太正确,只能得到最后一个方括号
You can't have a dynamic number of captures; 您不能动态捕获数量。 the number of captures is exactly equal to the number of capture parenthesis pairs (
(?:...)
don't count). 捕获的数量完全等于捕获括号对的数量(
(?:...)
不包括(?:...)
)。 You have two capture parenthesis pairs, that means you get two captures - no more, no less. 您有两个捕获括号对,这意味着您将获得两个捕获-不多也不少。
To handle variable number of matches, use submatches (in a replace with a function, if your language supports that), or split. 要处理可变数量的匹配项,请使用子匹配项(如果您的语言支持,则用函数替换)或拆分。
You haven't labeled with a programming language, so this is as specific as I can go. 您没有使用编程语言来标记,所以这是我所能做到的。
You can't repeat groups in a regex. 您不能在正则表达式中重复组。 You can write them out a number of times though.
您可以多次写出来。 This works for up to three groups in square brackets.
这在方括号中最多适用于三组。 You can add more if you like.
您可以根据需要添加更多内容。
(\w+)\[(\w+)\](?:\[(\w+)\])?(?:\[(\w+)\])?
This should do ([\\w]+)(?:\\[([\\w]+)\\]\\+)?
这应该做
([\\w]+)(?:\\[([\\w]+)\\]\\+)?
http://regex101.com/r/mF8pC8/3 http://regex101.com/r/mF8pC8/3
Changes from original regex - removed extra capture and added \\
before last +
. 与原始正则表达式的更改-删除了多余的捕获,并在last
+
之前添加了\\
。
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)
You can not have dynamic number of captures with php regexp... 您无法使用php正则表达式动态捕获数量...
Why not just, write something like: explode('[',strtr('name[one][two][three]', [']'=>'']))
- it will give you desired result. 为什么不这样写呢?
explode('[',strtr('name[one][two][three]', [']'=>'']))
-它会给您想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.