Home > Java > javaTutorial > How Can Regular Expressions Extract Integers from Text Strings?

How Can Regular Expressions Extract Integers from Text Strings?

DDD
Release: 2024-12-07 19:09:14
Original
671 people have browsed it

How Can Regular Expressions Extract Integers from Text Strings?

Extracting Integers from Text using Regular Expressions

In this article, we explore how to extract integer values from a given text string. Regular expressions provide a powerful tool for this task.

Problem:

Consider a string containing an English sentence with embedded numbers. We aim to isolate these numbers and store them as an array of integers. Can regular expressions assist us in this process?

Solution:

Utilizing Sean's solution, we modify it slightly:

LinkedList<String> numbers = new LinkedList<String>();

Pattern p = Pattern.compile("\d+");
Matcher m = p.matcher(line);
while (m.find()) {
    numbers.add(m.group());
}
Copy after login

Enhanced Extraction:

To refine our extraction, we can employ a regular expression that captures both positive and negative numbers:

Pattern p = Pattern.compile("-?\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
    System.out.println(m.group());
}
Copy after login

This modified regular expression ensures that both types of numbers are extracted. The output will display both "-2" and "12."

The above is the detailed content of How Can Regular Expressions Extract Integers from Text Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template