Reputation: 33
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:
the regex expression should return the following values respectively from the above Strings
Upvotes: 1
Views: 189
Reputation: 521674
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
.
Upvotes: 0
Reputation: 444
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))"
Upvotes: 2