Braj
Braj

Reputation: 46881

Regex to split based on specific comma

I have simple requirement. I have a small string and want to split based on comma but only that are outside the parenthesis.

Sample Input

SUM(Col1) OVER (PARTITION BY Col2, Col3) AS Col5,SUM(Col2) OVER (PARTITION BY Col2) AS Col4

Expected output:

SUM(Col1) OVER (PARTITION BY Col2, Col3) AS Col5
SUM(Col2) OVER (PARTITION BY Col2) AS Col4

Thanks

Upvotes: 1

Views: 54

Answers (2)

vks
vks

Reputation: 67988

,(?=([^()]*\([^()]*\))*[^()]*$)

Try this.See demo.

http://regex101.com/r/pQ9bV3/31

P.S this assumes there are no nested ( or ).


Here is optimized regex that worked for me

,(?=[^)]+\()

Online demo

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174874

Through negative lookahead assertion. For this case negative lookahead assertion is the best option rather than positive lookahead.

,(?![^()]*\))

The above regex would match all the commas only if it's not followed by,

  • [^()]* Any character but not of ( or ) zero or more times.
  • \) A closing paranthesis.

DEMO

Upvotes: 2

Related Questions