Home > Back-end >  How to match regex with conditions?
How to match regex with conditions?

Time:03-19

"Fingerprint (rear-mounted, region dependent), accelerometer, proximity, compass"

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:

  1. Fingerprint (rear-mounted,
  2. region dependent),
  3. accelerometer,
  4. proximity

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

CodePudding user response:

Here is one way to do so:

(?:[^(,] (?:\([^)]*\))?) ?(?:, |$)

See the online demo here.

const pattern = /(?:[^(,] (?:\([^)]*\))?) ?(?:, |$)/g;
const str = 'Fingerprint (rear-mounted, region dependent), accelerometer, proximity, compass';

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.
  • Related