Reputation: 7008
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 enumerated list of items, and they type in the numbers for the items they want to select, separated by a space. Here is an example:
1 yorkshire terrier
2 staffordshire terrier
3 goldfish
4 basset hound
5 hippopotamus
Type the numbers that correspond to the words you wish to exclude: 3 5
The enumerated list of items can be a just a few elements or several hundred. The current regex I'm using looks like this ^|\\.\\s+)\\d+\\s+
, but I know it's wrong. I don't fully understand regular expressions yet, so if you can explain what it is doing that would be helpful too!
Upvotes: 2
Views: 6671
Reputation: 76
Pattern pattern = new Pattern(^([0-9]*\s+)*[0-9]*$)
Explanation of the RegEx:
This treats all of the following inputs as valid:
etc.
Upvotes: 6
Reputation: 89584
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.
Upvotes: 0
Reputation: 425208
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));
Upvotes: 0
Reputation: 354714
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 \\
.
Upvotes: 2