Regex non-greedy and global modifiers not working as expected with JavaScript .match

Viewed 29

I'm trying to create a Regex that will return text that is wrapped by parentheses. For example, in the following string combination:

const regexString = "asdf (asdfasd asdfas) asdfasd asdfasd asdf(asfda) asdfasd (asdfasd)"

the regex should return only: (asdfasd asdfas), (asfda), and (asdfasd) as individual capture groups.

Using regex101.com I was able to put this combination together:

/(\(.+\))/gU

This regex combo works, but when I try to implement this in Javascript .match or even with .exec, I am simply returned the entire string.

For example,

regexString.match(/(\(.+\).*?)/g)

returns the entire string.

I believe the issue has to do my use of the ungreedy .*? modifier and the global /g modifier. Both of these are used in the working example from regex101.com, but I haven't been able to determine exactly why these modifiers or possibly the regex are not functioning the same when I try to use them in Javascript directly.

Thank you for any insight!

2 Answers

I believe you dont get entire string, but by using greedy modifier you get all characters between first opening and last closing parentheses. In your example the returned value is array with single string:

['(asdfasd asdfas) asdfasd asdfasd asdf(asfda) asdfasd (asdfasd)']

You need to change your regex with nongreedy ? to get least possible amount of characters between parentheses

regexString.match(/(\(.+?\).*?)/g)

Then the returned result will be:

['(asdfasd asdfas)', '(asfda)', '(asdfasd)']

what you're searching for is /\([^)]*\)/g

  • \( : will match the opening parenthese
  • [^)] : will match any non closing parenthese
  • * : will match many times the last character
  • \) : will match a closing parenthese
Related