1

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?

3
  • 1
    At this point you're better off not using a regex. Write a parser. Commented Mar 29, 2022 at 7:16
  • 2
    The easiest regex approach is with alternation: ^(?:\{\w+=\w+(?:,\w+=\w+)*\}|\w+=\w+(?:,\w+=\w+)*)$ Commented Mar 29, 2022 at 7:19
  • Thank you. Alternation approach looks more readable than using lookahead or lookbehind! Commented Mar 29, 2022 at 12:45

2 Answers 2

1

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.

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

1 Comment

Thank you for your response! This helped me understand lookbehind and lookahead and now I'm clear about how they work in the context of regex. But I'm going to use the 'Alternation' approach which looks more readable and I'm going to accept your answer since it was extremely helpful.
0

How about this?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.