简体   繁体   中英

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

for Example if these are the sample Strings:

  • "Some Sample String (Value 1) (more) Something (Value 2)"
  • "Some Sample String (Val One), Something (Val Two) "
  • "Some Sample String (VOne) - Something (VTwo)"

the regex expression should return the following values respectively from the above Strings

  • "Value 2"
  • "Val Two"
  • "VTwo"

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))"

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. If so, then we take the regex replacement, otherwise we assign NO MATCH .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM