查找模式的最后一次出现

dvl*_*lpr 2 javascript regex

我正在尝试匹配字符串中最后一次出现的模式.

我想在下面的字符串中得到括号中的最后一个字:

(不要与此匹配)而不是这个(但这个)

我试过以下,

\s(\((.*?)\))(?!\))
Run Code Online (Sandbox Code Playgroud)

但这与两次事件相匹配,而不仅仅是最后一次.是否可以匹配最后一个?

nha*_*tdh 6

匹配括号中的所有字符串/\(.*?\)/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)"
Run Code Online (Sandbox Code Playgroud)

不想要()结果吗?只是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"
Run Code Online (Sandbox Code Playgroud)

使用.*搜索模式的最后一个实例

这是一个简单的正则表达式的替代解决方案.我们利用贪婪属性.*来搜索最远的实例匹配模式\((.*?)\),其中结果被捕获到捕获组1中:

/^.*\((.*?)\)/
Run Code Online (Sandbox Code Playgroud)

请注意,此处不使用全局标志.当正则表达式是非全局的(仅查找第一个匹配项)时,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"
Run Code Online (Sandbox Code Playgroud)

^当模式.*\((.*?)\)无法与索引0匹配时,这是一种优化以防止引擎"碰撞"以搜索后续索引.