Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex ending word not found

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?

like image 259
ps0604 Avatar asked May 08 '26 08:05

ps0604


2 Answers

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.

like image 106
anubhava Avatar answered May 09 '26 22:05

anubhava


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"/>
like image 43
Wiktor Stribiżew Avatar answered May 10 '26 00:05

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!