Let's say you have a string with the phrase ("He has 2 cats")
Is there a way for the program to take out the integers in the string and assign each integer to a variable?
Let's say you have a string with the phrase ("He has 2 cats")
Is there a way for the program to take out the integers in the string and assign each integer to a variable?
Something like this should work.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
public class RegexExamples {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("He has 2 cats");
List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
}
}
I think the most variable-like way to handle this would be to parse out the Integers and put them into a Map.
Something like this, note that it might break on certain unexpected inputs. If you have any question on a certain part of this code feel free to ask:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "He has 2 dogs, 5 cats, wait.. make that 6 cats, and 1000 mice!";
Map<String, Integer> map = parseNounCounts(input);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
private static final Pattern NOUN_COUNT_PATTERN = Pattern.compile("(?:^|\\s)(\\d+)\\s+([a-zA-Z]*)");
/**
* Parses integers, and the words they precede, from the given input string and returns the map of
* words to their preceding integer count in order of discovery.
*/
public static LinkedHashMap<String, Integer> parseNounCounts(String input) {
Matcher matcher = NOUN_COUNT_PATTERN.matcher(input);
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
while (matcher.find()) {
String key = matcher.group(2);
int value = Integer.parseInt(matcher.group(1));
if (map.containsKey(key)) {
String newKey;
for (int i = 2; map.containsKey(newKey = key + '#' + String.valueOf(i)); i++)
;
key = newKey;
}
map.put(key, value);
}
return map;
}
}
Running main prints the following:
dogs : 2
cats : 5
cats#2 : 6
mice : 1000