Home >Java >javaTutorial >How to Extract a Number from a String in Java Using Regular Expressions?
How to Extract a Value from a String Using Regular Expressions in Java
Question:
Given a series of strings structured as "[some text] [some number] [some more text]", how can we extract the "some number" value using Java's regular expression (regex) classes? We're primarily interested in a single instance of "some number," and the source strings are short.
Answer:
To achieve the extraction, follow these steps:
Create a Pattern Object:
Define a Pattern object using Pattern.compile(regex) with your desired regular expression. For example:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
Create a Matcher Object:
Check for a Match:
Extract the Value:
Example:
Matcher m = p.matcher("Testing123Testing"); if (m.find()) { System.out.println(m.group(2)); // prints 123 }
Regex Refinements:
For extracting the first number, use the following regular expression:
^\D+(\d+).*
This matches strings where a non-digit character is followed by one or more digits and additional characters. m.group(1) will retrieve the "some number" value.
The above is the detailed content of How to Extract a Number from a String in Java Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!