split string on commas, ignore single quote and comma in single quote

Viewed 80

I have a string

10013751290,STUBBY'S GYM,HELLO ( Mate (, HEY 'duran,duran',this is [ possible[ ] ]possible ,1232424

I want to split by , using regex in java, so the result I would be expecting is like

10013751290

STUBBY'S GYM

HELLO ( Mate (

HEY 'duran,duran'

this is [ possible[ ] ]possible

1232424

I tried the following expression ,(?=(?:[^']*\'[^']*\')*[^']*$)

I am getting only 4 matches whereas I should be getting 6.

Please can some one help. I have checked and its not a duplicate, slightly different.

2 Answers

You want to ignore a ' that is an apostrophe, thus, you need to add this as an alternative to the pattern that matches any char but ', that is, [^'] -> (?:[^']|\b'\b). Or, (?:[^']|(?<=[a-zA-Z])'(?=[a-zA-Z])) or a fully Unicode (?:[^']|(?<=\p{L})'(?=\p{L})) (if supported) to only match ' in between alphabetic chars, letters.

\s*,\s*(?=(?:(?:(?:[^']|\b'\b)*'){2})*(?:[^']|\b'\b)*$)

See the regex demo. Details:

  • \s*,\s* - a comma enclosed with zero or more whitespace chars
  • (?=(?:(?:(?:[^']|\b'\b)*'){2})*(?:[^']|\b'\b)*$) - a positive lookahead that requires, immediately to the right of the current location:
    • (?:(?:(?:[^']|\b'\b)*'){2})* - zero or more occurrences of two repetitions of
      • (?:[^']|\b'\b)* - zero or more occurrences of any char other than a ' or a ' in between any word chars
      • ' - a single quotation mark
    • (?:[^']|\b'\b)* - zero or more occurrences of any char other than a ' or a ' in between any word chars
    • $ - end of string.

you can try something like this :

(?<=^|,)(((?:\s|\w)*'(?:\w|,)*')|.*?)(?=$|,)

result

10013751290
STUBBY'S GYM
HELLO ( Mate (
 HEY 'duran,duran'
this is [ possible[ ] ]possible 
1232424

see demo

Related