Extracting Values Using Regular Expressions in Java
This article addresses the need to extract specific text segments using regular expressions in Java. The context revolves around isolating the numerical component enclosed within the "[some number]" pattern from a series of strings.
To achieve this, we employ the Java regex classes. A regular expression, such as "^([a-zA-Z] )([0-9] )(.*)", is constructed to identify the desired pattern.
The core Java calls for applying this regular expression on source data are:
A comprehensive example is provided:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)"); public static void main(String[] args) { Matcher m = p.matcher("Testing123Testing"); if (m.find()) { System.out.println(m.group(0)); // whole matched expression System.out.println(m.group(1)); // Testing System.out.println(m.group(2)); // 123 System.out.println(m.group(3)); // Testing } }
For scenarios where the numeric component may include a sign, a modified regular expression like "^D (-?d ).*", should be used.
The above is the detailed content of How Can I Extract Numerical Values from Strings Using Java Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!