Regular expression split by comma

Viewed 54

I am trying to use this expression:

([A-Z])*[=]?([a-z])*, ([A-Z])*[=]?([a-z])*

to split the following text:

MESSAGE=This , is message., STATUS=400

into a comma separated string like this:

MESSAGE=This , is message.
STATUS=400
2 Answers

If your regex engine supports lookaheads you can use

\s*,\s*(?=[A-Z]+=)

See the regex demo.

Details:

  • \s*,\s* - a comma enclosed with zero or more whitespaces on both ends
  • (?=[A-Z]+=) - a positive lookahead that makes sure there are one or more uppercase ASCII letters and then a = sign immediately to the right of the current location.

If you are using a programming language, then a regex find all approach might be well suited here. For example, on Python we can try:

inp = "MESSAGE=This , is message., STATUS=400"
parts = re.findall(r'([A-Z]+\s*=.*?)\s*(?=,\s*[A-Z]+\s*=|$)', inp)
print(parts)  # ['MESSAGE=This , is message.', 'STATUS=400']
Related