[英]Regex, match the last pattern
How can you match the last occurrence of a regex pattern? 如何匹配最后一次出现的正则表达式?
For example, how can I match [XXX] in: 例如,我如何匹配[XXX]:
data[X][XX][XXX]
Where X, XX, XXX could be assigned randomly. 其中X,XX,XXX可以随机分配。
I already tried to use a negative lookahead 我已经尝试使用否定前瞻
\[.*?\](?!.*?\[.*?\])
But the first [ with the last ] will be matched what would not give the correct result. 但是第一个[与最后一个]将匹配不能给出正确结果的东西。
The reason why you get such a result is that the .
你得到这样一个结果的原因是.
matches a [
and ]
and any other char other than line break chars. 匹配[
和]
以及除换行符之外的任何其他字符。 You may replace the lazy dot with a negated character class [^][]
: 您可以使用否定字符类[^][]
替换延迟点:
\[[^][]*\](?!.*?\[[^][]*\])
See the regex demo 请参阅正则表达式演示
Depending on the regex flavor, you may need to escape [
and ]
in the character class (in JS, ]
must be escaped ( [^\\][]
) and in Java/ICU you need to escape both ( [^\\]\\[]
)). 根据正则表达式的风格,你可能需要转义[
和]
在字符类中(在JS中]
必须被转义( [^\\][]
)而在Java / ICU中你需要转义它们( [^\\]\\[]
))。
You can try this for simplicity: 你可以试试这个简单:
.*(\[.*\])
It will match upto the last occurance but will capture the last occurrence of [anything]
in group 1 and won't have to look ahead 它将匹配到最后一次出现,但将捕获组1中[anything]
最后[anything]
的[anything]
,并且不必向前看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.