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()); }
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()); }
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!