Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/(\(.+\))/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!

>Solution :

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)']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading