I would like to verify the syntax of an input field with a regex. The field should accept text like the following examples:
Something=Item1,Item2,Item3 someOtherThing=Some_Item
There has to be a word, a =
sign and a list of comma separated words. The list must contain at least one entry. So abc=
should be invalid, but abc=123
is valid.
I am using a framework which allows a regular expression (Java) to mark the input field as valid or invalid. How can I express this rule in a regex?
With the aid of https://stackoverflow.com/a/65244969/7821336, I am able to validate the comma separated list. But as soon as I prepend my stuff with the assignment, the regex does not work any longer:
(w+)=((?:w+)+),? // does not work!
Advertisement
Answer
You are not repeating the comma in the group, that is why it does not work when having multiple comma separated values.
If you want to get separate matches for the key and the values, you can use the G
anchor.
(?:^(w+)=|G(?!^))(w+)(?:,|$)
Explanation
(?:
Non capture group^(w+)=
Assert start of string and capture 1+ word chars in group 1|
OrG(?!^)
Assert the postion at the end of the previous match, not at the start
)
Close non capture group(w+)
Capture group 2, match 1+ word characters(?:,|$)
Match either,
or assert end of string
For example:
String regex = "(?:^(\w+)=|\G(?!^))(\w+)(?:,|$)"; Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); String[] strings = {"Something=Item1,Item2,Item3", "someOtherThing=Some_Item", "Something="}; for (String s : strings) { Matcher matcher = pattern.matcher(s); while (matcher.find()) { String gr1 = matcher.group(1); String gr2 = matcher.group(2); if (gr1 != null) { System.out.println("Group 1: " + gr1); } if (gr2 != null) { System.out.println("Group 2: " + gr2); } } }
Output
Group 1: Something Group 2: Item1 Group 2: Item2 Group 2: Item3 Group 1: someOtherThing Group 2: Some_Item