"Fingerprint (rear-mounted, region dependent), accelerometer, proximity"
Above is the string of sensors in a device. I'm trying to match every sensor. The problem is that when I match above using /.+?,/g, The matches are:
I'm getting 4 sensors here instead of three. Because, of course, my pattern matches these. What I want to do is that when a , is preceded by (, then I want to match ), and when not preceded by (, I want to match ,
I think I need to use lookarounds here. But I can't get them to work for me. I tried multiple regexes. It's silly to paste them all here :)
I'm using JavaScript
Here is one way to do so:
(?:[^(,]+(?:\([^)]*\))?)+?(?:, |$)
See the online demo here.
const pattern = /(?:[^(,]+(?:\([^)]*\))?)+?(?:, |$)/g;
const str = 'Fingerprint (rear-mounted, region dependent), accelerometer, proximity';
const matches = str.matchAll(pattern)
for (const match of matches) {
console.log(match[0]);
}
(?:)+?: Non capturing group, repeated between one and unlimited times, as few as possible.
[^(,]: Matches any character other than ( or ,.(?:)?: Optional non capturing group.
\(: Matches (.[^)]*: Matches any character other than ), between zero and unlimited times, as much as possible.\): Matches ).(?:): Non capturing group.
, : Matches , .|: Or.$: Matches the end of the string.