[Solved] Extract two numbers from a String with the Java Matcher class

Introduction

The Java Matcher class is a powerful tool for extracting data from strings. It can be used to extract two numbers from a string, which can be useful for a variety of applications. This tutorial will explain how to use the Matcher class to extract two numbers from a string. It will also provide examples of how to use the Matcher class to extract two numbers from a string. Finally, it will provide some tips and tricks for getting the most out of the Matcher class.

Solution

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractNumbers {
public static void main(String[] args) {
String input = “The numbers are 12 and 45”;
Pattern pattern = Pattern.compile(“\\d+”);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}

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