Javascript regex end word not found

In this regex, I need to match a trailing word starting with '(', ')'

or ','

.

Regex:

/[\(\),].*$/

      

For example, given the text, (aaa,bbb)ccc

I need to get )ccc

. However, it returns all text. What's wrong with this regex?

+3


source to share


3 answers


You can use:

'(aaa,bbb)ccc'.match(/[(),][^(),]+$/)
//=> [")ccc"]

      



[^(),]+

a negation pattern that matches any character specified in [^(),]

.

The problem with [(),].*$

is that it matches the very first one (

in the input and matches all the way.

+2


source


You can also consider using a capture group when consuming all characters up to the first (

, )

or ,

:

.*([(),].*)$

      

.*

will consume as many characters as it can, then any character in that character class [(),]

and then the rest of the characters to the end.



The value )ccc

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

Run codeHide result


+1


source


Try this regex:

/[(,)][^(,)]*$/

      

0


source







All Articles