捕获字符串中方括号占位符内不确定数量的分隔值
我有以下正则表达式:
\[([^ -\]]+)( - ([^ -\]]+))+\]
此匹配成功:
[abc - def - ghi - jkl]
但匹配是:
Array
(
[0] => [abc - def - ghi - jkl]
[1] => abc
[2] => - jkl
[3] => jkl
)
我需要的是这样的:
Array
(
[0] => [abc - def - ghi - jkl]
[1] => abc
[2] => - def
[3] => def
[4] => - ghi
[5] => ghi
[6] => - jkl
[7] => jkl
)
我可以在 C# 中查看组“捕获”来做到这一点。我怎样才能在 PHP 中做到这一点?
I have the following regex:
\[([^ -\]]+)( - ([^ -\]]+))+\]
This match the following successfully:
[abc - def - ghi - jkl]
BUT the match is:
Array
(
[0] => [abc - def - ghi - jkl]
[1] => abc
[2] => - jkl
[3] => jkl
)
What I need is something like this:
Array
(
[0] => [abc - def - ghi - jkl]
[1] => abc
[2] => - def
[3] => def
[4] => - ghi
[5] => ghi
[6] => - jkl
[7] => jkl
)
I'm able to do that in C# looking at the groups "captures". How can I do that in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这不是正则表达式的工作。匹配
\[([^\]]*)\]
,然后爆炸
通过" - "
第一次捕获。This is not the job for the regexp. Match against
\[([^\]]*)\]
, thenexplode
the first capture by the" - "
.假设示例字符串中的标记从不包含空格,并且是字母数字:
输出:
Assuming the tokens in your sample string never contain spaces, and are alphanumeric:
Output:
SPL preg_match_all 将返回从 < 的索引 1 开始的正则表达式组代码>$matches 变量。如果您只想获取第二组,您可以使用
$matches[2]
例如。语法:
结果:
PS 此答案是在通过 Google 搜索定向到此处后针对问题标题的上下文发布的。这是我在搜索该主题时感兴趣的信息。
SPL preg_match_all will return regex groups starting on index 1 of the
$matches
variable. If you want to get only the second group you can use$matches[2]
for example.Syntax:
Result:
P.S. This answer is posted for the context of the question title after being directed here by a Google search. This was the information I was interested in when searching for this topic.
要将匹配项分组,请使用括号。 EG:
$matches
将是['bob']
$matches
将是['bob','b','o ','b']
To group your matches, use parenthesize. EG:
$matches
will be['bob']
$matches
will be['bob','b','o','b']
要匹配方括号占位符内不确定数量的分隔值,请匹配占位符的开头并向前查找以验证占位符的其余部分,或者从上一个匹配以
\G
元字符后跟定界子字符串;那么你就可以匹配所寻求的值。代码:(演示)
输出:
To match an indeterminant number of delimited values inside of a square-braced placeholder, either match the start of the placeholder and lookahead to validate the remainder of the placeholder or match from where the previous match ended with the
\G
metacharacter followed by the delimiting substring; then you can just match the sought values.Code: (Demo)
Output: