Home >Java >javaTutorial >How Can Java Regular Expressions Extract Numerical Values from Strings?
Utilizing Regular Expressions to Extract Values in Java
Seeking to extract numerical values from strings in the format "[some text] [some number] [some more text]", this article leverages Java's regular expression classes to accomplish the task.
The desired regular expression can vary, but the Java calls remain consistent. To use a regular expression string on source data, follow these steps:
Here's an example that extracts the first numerical value using the regular expression "^D (d ).*":
private static final Pattern p = Pattern.compile("^\D+(\d+).*"); public static void main(String[] args) { Matcher m = p.matcher("Testing123Testing"); if (m.find()) { System.out.println("Extracted number: " + m.group(1)); } }
This code will print "123" as the extracted number.
The above is the detailed content of How Can Java Regular Expressions Extract Numerical Values from Strings?. For more information, please follow other related articles on the PHP Chinese website!