-2

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!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Dog
  • 2,726
  • 7
  • 29
  • 66
  • I believe it matches zero or more characters, which would match the text in-between the parentheses – Dog Sep 09 '22 at 20:30
  • 1
    It matches 1 or more of any character except line break and it is greedy in nature. – anubhava Sep 09 '22 at 20:34
  • 1
    Your title says that the non-greedy modifier isn't working, but the problem is that you're not using the non-greedy modifier in your regexp. `.+` is greedy, `.+?` would be non-greedy. – Barmar Sep 09 '22 at 20:38
  • I believe in regex101 'U' is non-greedy so it works. – Dog Sep 09 '22 at 20:39

2 Answers2

2

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)']
Nikes
  • 1,094
  • 8
  • 13
  • Thank you for your help. It makes sense. Basically adding the non-greedy modifier to the characters in between the parens is telling the regex to limit each match to the first instance where the specified regex combination exists, so it captures the individual parens groups and not the larger paren group. Thank you! – Dog Sep 09 '22 at 20:43
0

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