In this regex , I need to match an ending word that starts with '(', ')' or ','.
Regex :
/[\(\),].*$/
For example, given the text (aaa,bbb)ccc I need to obtain )ccc. Still, it returns the entire text. What's wrong with this regex?
You can use:
'(aaa,bbb)ccc'.match(/[(),][^(),]+$/)
//=> [")ccc"]
[^(),]+ is negation pattern that matches any character but any listed in [^(),].
Problem with [(),].*$ is that it matches very first ( in input and matches till end.
You can also consider using capturing group while consuming all the characters up to the first (, ) or ,:
.*([(),].*)$
.* will consume as many characters as it can, then any character in this character class [(),], and then the rest of the characters up to the end.
The )ccc value will be stored in Group 1:
var re = /.*([(),].*)$/;
var str = '(aaa,bbb)ccc';
if ((m = re.exec(str)) !== null) {
document.getElementById("res").innerHTML = m[1];
}
<div id="res"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With