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.

5
  • 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? Commented Aug 7, 2017 at 13:06
  • Sure, I need to capture that to inject data in tables, with INSERT INTO TABLE (parameters) VALUES (values) Commented Aug 7, 2017 at 13:10
  • You might want to look at the following: stackoverflow.com/questions/1293147/… Commented Aug 7, 2017 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 Commented Aug 7, 2017 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. Commented Aug 7, 2017 at 14:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

To be honest, I am almost new to regex and the \2 was the thing I have searched so far. Thank you very much for your answer, have a nice day.
@v01dv01d You are most welcome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.