3

I am trying to create a regex expression that would match one or multiple variable value assignments on the same line. I am using the following expression:

([a-z][a-zA-Z0-9-]*)=(('(\'|[^\'])*')|("(\"|[^"])*"))

For example, if I have the following string as input:

a="xyz" b="hello world"

And using the following code:

Matcher matcher = rules.get(regex).matcher(input);
int start = 0;

while (matcher.find(start)) {
    System.err.println(matcher.group(0));

    start = matcher.end();
}

It should give me two seperate results:

1. a="xyz"
2. b="hello world"

But it only returns one, the entire input string.

a="xyz" b="hello world"

It seems to be taking xyz" b="hello world as the inner part. How can I resolve this?

4
  • Your alternatives are off, see ([a-z][a-zA-Z0-9-]*)=(('([^']*)')|("([^"]*)")), demo Commented Mar 4, 2020 at 21:43
  • Can you have escape " like a="xyz" b="hell\"o world" Commented Mar 4, 2020 at 21:49
  • @WiktorStribiżew It was a mistake in typing the pattern, check again because mine is a bit different. Commented Mar 4, 2020 at 21:53
  • @anubhava Yea. I had a small mistake in my code. Commented Mar 4, 2020 at 21:54

1 Answer 1

2

You may use

(?s)([a-z][a-zA-Z0-9-]*)=(?:'([^\\']*(?:\\.[^\\']*)*)'|"([^"\\]*(?:\\.[^"\\]*)*)")

See the regex demo

In Java,

String regex = "(?s)([a-z][a-zA-Z0-9-]*)=(?:'([^\\\\']*(?:\\\\.[^\\\\']*)*)'|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")";

Details

  • (?s) - inline Pattern.DOTALL embedded flag option that matches . match line break chars, too
  • ([a-z][a-zA-Z0-9-]*) - Group 1
  • = - an equals sign
  • (?:'([^\\']*(?:\\.[^\\']*)*)'|"([^"\\]*(?:\\.[^"\\]*)*)") - a non-capturing group matching one of the two alternatives:
    • '([^\\']*(?:\\.[^\\']*)*)' - ', then any amount of chars other than \ and ' followed with 0+ repetitions of any escape sequence followed with 0+ chars other than \ and '
    • | - or
    • "([^"\\]*(?:\\.[^"\\]*)*)" - ", then any amount of chars other than \ and " followed with 0+ repetitions of any escape sequence followed with 0+ chars other than \ and " .
Sign up to request clarification or add additional context in comments.

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.