I'm trying to parse an input string of type "move 2 up;1 right;1 down"
using a regex, but I can't seem to figure out how to get all groups of commands while ignoring the "move" keyword.
My regex is:
(?:\bmove\b) ((?<amount>[1-6]) (?<direction>(\bup\b|\bright\b|\bdown\b|\bleft\b))(?:;?))+
and my Java code is this:
String str = "move 1 right;2 left;";
String regex = "(?:\\bmove\\b) ((?<amount>[1-6]) (?<direction>(\\bup\\b|\\bright\\b|\\bdown\\b|\\bleft\\b))(?:;?))+";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher match = pattern.matcher(str);
while (match.find()) {
String group = match.group(1);
System.out.println(group);
}
In the loop I would like to get the first command as "1 right"
and the second as "2 left"
. With the regex that I have now I only get the "2 left;"
. There are some examples of input here: https://regex101.com/r/Fg0hk3/3.
How do I fix my regex?
Ended up using 2 regex patterns, one for the full match and one for the tokens:
Full match:
(?:\bmove\b) ((?<amount>[1-6]) (?<direction>(\bup\b|\bright\b|\bdown\b|\bleft\b))(?:;?))+
Tokens:
(?<amount>[1-6]) (?<direction>(?:\bup\b|\bright\b|\bdown\b|\bleft\b))