简体   繁体   English

从正则表达式php捕获组中的倒数第二个字符开始

[英]Start at the penultimate character in capture group of regex php

I am trying to create a regex that only captures between the second to last and last occurrences of the surrounding characters (if you get what I mean). 我正在尝试创建一个仅捕获倒数第二个和最后一个出现在周围字符之间的正则表达式(如果您理解了我的意思)。

My regex so far is this: 到目前为止,我的正则表达式是:

\\[(.*?)]\\{(.*?)\\}/ig

This is my string: 这是我的字符串:

[don't touch me] random text [touchme]{Secondcapturegroup}

As you can see by this screenshot, it's capturing everything from [don't all the way to [touchme ]. 如您从该屏幕快照中所见,它捕获了从[don't完整到[touchme ]]的所有内容。 I want it to effectively ignore [don't touch me] random text 我希望它有效地忽略[don't touch me] random text

不要碰我

I'm still learning regex, but I know there must be something :) 我仍在学习正则表达式,但我知道一定有一些东西:)

You can use a character class that excludes the closing square bracket instead of using . 您可以使用不包含方括号的字符类,而不要使用. (and in this way the non-greedy quantifier *? is no more needed) (这样,就不再需要非贪婪的量词*?了)

\[([^]]*)]{([^}]*)}

In this way the attempt at the first opening square bracket will fail because the closing square bracket is not followed by an opening curly bracket. 这样,在第一个左方括号中的尝试将失败,因为在右方括号后没有左方花括号。

With your pattern you obtain a wrong result because the regex engine parse your string from the left and try to succeed at each position (so the first position always win). 使用您的模式,您会得到错误的结果,因为正则表达式引擎从左侧解析您的字符串,并尝试在每个位置成功(因此第一个位置总是获胜)。

Note that the i modifier is useless. 注意, i修饰符是无用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM