0

My string:

AA,$,DESCRIPTION(Sink, clinical),$

Wanted matches:

AA
$
DESCRIPTION(Sink, clinical)
$

My regex sofar:

\+d|[\w$:0-9`<>=&;?\|\!\#\+\%\-\s\*\(\)\.ÅÄÖåäö]+

This gives

AA
$
DESCRIPTION(Sink
clinical)

I want to keep matches between ()

https://regex101.com/r/MqFUmk/3

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joe
  • 4,274
  • 32
  • 95
  • 175

4 Answers4

1

Here's my attempt at the regex

\+d|[\w$:0-9`<>=&;?\|\!\#\+\%\-\s\*\.ÅÄÖåäö]+(\(.+\))?

I removed the parentheses from within the [ ] characters, and allowed capture elsewhere. It seems to satisfy the regex101 link you posted.

Depending on how arbitrary your input is, this regex might not be suitable for more complex strings.

Alternatively, here's an answer which could be more robust than mine, but may only work in Ruby.

((?>[^,(]+|(\((?>[^()]+|\g<-1>)*\)))+)
Community
  • 1
  • 1
Adam
  • 4,445
  • 1
  • 31
  • 49
  • Problem is if you add another ending parenthesis, it matches from the first parenthesis to the last one. I would suggest replacing the capture group with `(\(.+?\))?`, making the inner parenthesis match lazy. In this case, the problems becomes if you have inner parenthesis such as `(a(b)c)`, which would not be matched correctly. – Antony Feb 15 '17 at 20:41
1

That one seems to work for me?

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

https://regex101.com/r/hLyJm5/2

Hope this helps!

nibnut
  • 3,072
  • 2
  • 15
  • 17
1

Personally, I would first replace all commas within parentheses () with a character that will never occur (in my case I used @ since I don't see it within your inclusions) and then I would split them by commas to keep it sweet and simple.

myStr = "AA,$,DESCRIPTION(Sink, clinical),$";            //Initial string
myStr = myStr.replace(/(\([^,]+),([^\)]+\))/g, "$1@$2"); //Replace , within parentheses with @
myArr = myStr.split(',').map(function(s) { return s.replace('@', ','); }); //Split string on ,
//myArr -> ["AA","$","DESCRIPTION(Sink, clinical)","$"]

optionally, if you're using ES6, you can change that last line to:

myArr = myStr.split(',').map(s => s.replace('@', ','));  //Yay Arrow Functions!

Note: If you have nested parentheses, this answer will need a modification

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
0

At last take an aproximation of what you need:

\w+(?:\(.*\))|\w+|\$

https://regex101.com/r/MqFUmk/4

Álvaro Touzón
  • 1,247
  • 1
  • 8
  • 21