Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix regex to work with empty substrings

How to change the following regex:

(?:(^|,)(?<quote>"|)(?<value>.*?)(\k<quote>)(?=(,|$)))

which works with:
1,1,-1 … I get "1","1","-1"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and works with:
"1","1","-1" … I get "1","1","-1"


but it doesn’t work as expected when one or more or the substrings are empty:

,1,-1 …in such case I need to get: "", "1", "1"

,"1","-1" …in such case I need to get: "", "1", "1"

,"1", …in such case I need to get: "", "1", ""

,, …in such case I need to get: "","",""

Is that possible?

>Solution :

You can use

(?<=,|^)(?<quote>"?)(?<value>.*?)\k<quote>(?=,|$)

See the regex demo.

Details:

  • (?<=,|^) – start of string or a location right after a comma
  • (?<quote>"?) – an optional double quote captured into Group "quote"
  • (?<value>.*?) – Group "value": any zero or more chars other than line break chars as few as possible
  • \k<quote> – same char as in Group "quote"
  • (?=,|$) – a location right before a comma or end of string.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading