查找模式的最后一次出现

时间:2015-05-07 07:46:44

标签: javascript regex

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

我想在括号中的最后一个单词中输入以下字符串:

  

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

我尝试了以下内容,

\s(\((.*?)\))(?!\))

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

2 个答案:

答案 0 :(得分: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)"

不希望结果中出现()?只需使用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"

^是一项优化措施,可防止引擎沿着&#34;碰撞当模式.*\((.*?)\)无法与索引0匹配时搜索后续索引。

答案 1 :(得分:2)

您可以使用非捕获括号来使用以前的匹配:

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

相关问题