To use Matcher
you start by compiling a Pattern
, then you call matcher(String)
and then you see if it matches. Finally, you can parse the values. Something like,
String str = "views: 120 upvotes: 540";
Pattern p = Pattern.compile("views:\\s*(\\d+)\\s+upvotes:\\s*(\\d+)",
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
if (m.matches()) {
int views = Integer.parseInt(m.group(1));
int upvotes = Integer.parseInt(m.group(2));
System.out.printf("%d %d%n", views, upvotes);
}
Output is
120 540
solved Extract two numbers from a String with the Java Matcher class