[英]Find the last occurrence of a pattern
我正在尝试匹配字符串中最后一次出现的模式。
我想在下面的字符串中得到括号中的最后一个字:
(不要与此匹配)而不是这个(但这个)
我试过以下,
\s(\((.*?)\))(?!\))
但这与两次事件相匹配,而不仅仅是最后一次。 是否可以匹配最后一个?
/\\(.*?\\)/g
所有字符串并对结果进行后处理 您可以匹配满足模式的所有字符串,并从结果数组中选择最后一个元素。 没有必要为这个问题提出复杂的正则表达式。
> "(Don't match this) and not this (but this)".match(/\(.*?\)/g).pop()
< "(but this)"
> "(Don't match this) and not this (but this) (more)".match(/\(.*?\)/g).pop()
< "(more)"
> "(Don't match this) and not this (but this) (more) the end".match(/\(.*?\)/g).pop()
< "(more)"
不希望结果中的()
? 只需使用slice(1, -1)
来摆脱它们,因为模式修复了它们的位置:
> "(Don't match this) and not this (but this)".match(/\(.*?\)/g).pop().slice(1, -1)
< "but this"
> "(Don't match this) and not this (but this) (more) the end".match(/\(.*?\)/g).pop().slice(1, -1)
< "more"
.*
搜索模式的最后一个实例 这是一个简单的正则表达式的替代解决方案。 我们利用.*
的贪婪属性来搜索最匹配的模式匹配\\((.*?)\\)
,其中结果被捕获到捕获组1中:
/^.*\((.*?)\)/
请注意,此处不使用全局标志。 当正则表达式是非全局的(仅查找第一个匹配项)时, match
函数返回捕获组捕获的文本以及主匹配。
> "(Don't match this) and not this (but this)".match(/^.*\((.*?)\)/)[1]
< "but this"
> "(Don't match this) and not this (but this) (more) the end".match(/^.*\((.*?)\)/)[1]
< "more"
当模式.*\\((.*?)\\)
无法与索引0匹配时, ^
是一种优化,以防止引擎“碰撞”以搜索后续索引。
您可以使用非捕获括号来使用以前的匹配:
var string="(Don't match this) and not this (but this) definitely not this";
var last_match=string.match(/(?:.*\()([^\)]*)(?:\)[^\(]*)/)[1];
使用Web开发人员控制台测试:
< var string="(Don't match this) and not this (but this) definitely not this";
< string.match(/(?:.*\()([^\)]*)(?:\)[^\(]*)/)[1]
>"but this"
以下是测试链接: https : //regex101.com/r/gT5lT5/2
如果您希望封闭括号成为匹配项的一部分,请查看https://regex101.com/r/gT5lT5/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.