Home >Java >javaTutorial >How Can I Extract Numbers from a String Using Java Regular Expressions?
Extracting Numbers from Strings Using Regular Expressions
To extract numbers from a string into an array of integers using regular expressions, you can utilize the Pattern and Matcher classes in Java. Here's a solution:
Solution:
Pattern p = Pattern.compile("-?\d+"); Matcher m = p.matcher("There are more than -2 and less than 12 numbers here"); LinkedList<Integer> numbers = new LinkedList<>(); while (m.find()) { numbers.add(Integer.parseInt(m.group())); } System.out.println(numbers); // prints [-2, 12]
Explanation:
Note that the -? part in the pattern handles negative numbers. If you don't want to allow negative numbers, you can remove it from the pattern.
The above is the detailed content of How Can I Extract Numbers from a String Using Java Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!