Home >Java >javaTutorial >How Can I Extract Numbers from a String Using Java Regular Expressions?

How Can I Extract Numbers from a String Using Java Regular Expressions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-26 17:12:15581browse

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:

  • p = Pattern.compile("-?\d "): This line compiles a regular expression pattern that matches any number, which can optionally have a leading negative sign.
  • m = p.matcher("..."): This line creates a Matcher object using the pattern and the specified string.
  • The while loop iterates over all matches found by the Matcher.
  • numbers.add(Integer.parseInt(m.group())): For each match, the numeric value is extracted using m.group() and then parsed into an integer using Integer.parseInt().
  • The result is a LinkedList of integers containing the extracted numbers.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn