I\'m asking the user for input through the Scanner
in Java, and now I want to parse out their selections using a regular expression. In essence, I show them an enu
To "parse out" the integers, you don't necessarily want to match the input, but rather you want to split it on spaces (which uses regex):
String[] nums = input.trim().split("\\s+");
If you actually want int
values:
List<Integer> selections = new ArrayList<>();
for (String num : input.trim().split("\\s+"))
selections.add(Integer.parseInt(num));
If you want to ensure that your string contains only numbers and spaces (with a variable number of spaces and trailing/leading spaces allowed) and extract number at the same time, you can use the \G
anchor to find consecutive matches.
String source = "1 3 5 8";
List<String> result = new ArrayList<String>();
Pattern p = Pattern.compile("\\G *(\\d++) *(?=[\\d ]*$)");
Matcher m = p.matcher(source);
while (m.find()) {
result.add(m.group(1));
}
for (int i=0;i<result.size();i++) {
System.out.println(result.get(i));
}
Note: at the begining of a global search, \G
matches the start of the string.
You want integers:
\d+
followed by any number of space, then another integer:
\d+( \d+)*
Note that if you want to use a regex in a Java string you need to escape every \
as \\
.
Pattern pattern = new Pattern(^([0-9]*\s+)*[0-9]*$)
Explanation of the RegEx:
This treats all of the following inputs as valid:
etc.