Home > Software design >  Java regular expression for if-then-else constructs
Java regular expression for if-then-else constructs

Time:03-30

I'm trying to write a regular expression that would match all the following pattern examples -

1) Name=John,Age=25
2) {Name=John,Age=25}
3) Name=John

Basically there has to be an equals to sign between two words or numbers followed by a comma (,) and then the pattern repeats. The pattern cannot end with any special characters apart from alphabets or numbers or a curly brace. Curly braces are optional and if a curly brace is used at the beginning of the pattern then there should be a closing curly brace as well and vice-versa, so the following patterns should not match -

1) Name=John!Age=25
2) {Name=John,Age=25
3) Name=John,Age=25}
4) Name=John,
5) Name=John=Age,25!

I'm trying to experiment with the following regular expression using lookaround but the pattern with curly braces does not match at all -

^(?:(?<=\{)(?=\})|(?<!\{)(?!\}))(?:\w =\w ,)*\w =\w }?$

What am I doing wrong here since the pattern with curly braces does not match at all?

CodePudding user response:

Looking at your regex I think this is not how lookahead or lookbehind is working. Since it is looking ahead or behind from a match. This is explained very well in this article https://javascript.info/regexp-lookahead-lookbehind.

With that I managed to create a pattern that works with lookahead and lookbehind.

((?<=\{)(\w =\w ,?) (?<!,)(?=\}))|^(\w =\w ,?) (?<!,)$

Here you can see that lookahead is trying to find a { behind and after the matching group (\w =\w ,?) (?<!,). The (?<!,) is just to prevent comma in the end.

Check the regex here https://regexr.com/6idl8.

CodePudding user response:

How about this?

\w =\w (?:,\w =\w )*|\{\w =\w (?:,\w =\w )*\}
  • Related