1

I have a list of values separated by commas like this :

bDestruction=True,bEmissionAlarme=False,bActionReinit=False,sNatureData="Sur évènement provenant d'ALIS ou SGP - Lignes BJ, IJ ou GMO",sCodeMsgExpliControle="MSG-G00033_P_ALIM_ME"

I want to capture both parameter and value, so I did this regex :

(?:([^=]*))="?([^,]*)(?:"|,)?

But as it does work in most cases, he does not for the example provided, as the text after sNatureData contains a comma. So the regex consider that it is the end of a couple {parameter=value} and throw an error.

What can be done ? Thanks in advance.

v01dv01d
  • 35
  • 2
  • 9
  • I think you might want to consider using a parser here. The comma content is correctly quoted, to let us know that what is inside the quotes should not be considered as a separator. Maybe you can give us greater context for where these keys/values are appearing? – Tim Biegeleisen Aug 07 '17 at 13:06
  • Sure, I need to capture that to inject data in tables, with INSERT INTO TABLE (parameters) VALUES (values) – v01dv01d Aug 07 '17 at 13:10
  • You might want to look at the following: https://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data – zerohero Aug 07 '17 at 13:22
  • Thanks for your answer, althought I am suprised that it does not exist any kind of Regex to capture text with condition like the presence of quotes – v01dv01d Aug 07 '17 at 14:30
  • Toto, I don't think this is quite the same question. It is very similar but I don't think this warrants a close for duplicate. And besides, for the very simple problem that this user is having, most answers there are too overly complex. – Kaamil Jasani Aug 07 '17 at 14:44

1 Answers1

1

I would suggest you follow the suggestions given to you in the comments and not use regex.

However, if you did need to do this using regex, the following should do the trick:

(.*?)=("?)([^"]+?)\2(?:,|$)
  • (.*?)= Captures the key to the left of the = sign. It only captures one key because the ? makes it match as few characters as possible.
  • ("?) Captures whether or not the value is in quotes.
  • ([^"]+?)\2(?:,|$)
    • ([^"]+?) Captures more than 1 character that is not ", but as few as possible.
    • \2(?:,|$) This stops either if there was a quote and it finds one again, or at the next comma or if the string has finished.

Test online

Kaamil Jasani
  • 464
  • 5
  • 11