[英]Regex to find last occurrence between the braces
I need regex expression to be used in JavaScript/ES6 to find the value between last occurrence of brackets in a String我需要在 JavaScript/ES6 中使用正则表达式来查找字符串中最后出现的括号之间的值
for Example if these are the sample Strings:例如,如果这些是示例字符串:
the regex expression should return the following values respectively from the above Strings正则表达式应分别从上述字符串返回以下值
str.match(/.*\((.*)\).*$/)[1]
Works for your use cases.适用于您的用例。
limit: This doesn't work for the strings which have nested brakets.限制:这不适用于具有嵌套小括号的字符串。 eg.例如。 "(Some Sample String (VOne) - Something (VTwo))" “(一些样本字符串(VOne) - 某事(VTwo))”
Here is a regex replace all approach.这是一个正则表达式替换所有方法。 We can match on the pattern ^.*\((.*?)\).*$
, which will consume everything from the start of the input up to, but not including, the final (...)
term.我们可以匹配模式^.*\((.*?)\).*$
,它将消耗从输入开始到但不包括最终(...)
项的所有内容。 We then capture the contents of that term and print out to the console.然后我们捕获该术语的内容并打印到控制台。
var input = "Some Sample String (Value 1) (more) Something (Value 2)"; var last = input.match(/\(.*\)/)? input.replace(/^.*\((.*?)\).*$/, "$1"): "NO MATCH"; console.log(last);
Note that I do an initial check with match
to ensure that the term has at least one (...)
term.请注意,我对match
进行了初步检查,以确保该术语至少有一个(...)
术语。 If so, then we take the regex replacement, otherwise we assign NO MATCH
.如果是这样,那么我们采用正则表达式替换,否则我们分配NO MATCH
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.