![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Regex to extract maximum numeric value from a string
The maximum numeric value is extracted from an alphanumeric string. An example of this is given as follows −
String = abcd657efgh234 Maximum numeric value = 657
A program that demonstrates this is given as follows −
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main (String[] args) { String str = "123abc874def235ijk999"; System.out.println("The string is: " + str); String regex = "\d+"; Pattern ptrn = Pattern.compile(regex); Matcher match = ptrn.matcher(str); int maxNum = 0; while(match.find()) { int num = Integer.parseInt(match.group()); if(num > maxNum) { maxNum = num; } } System.out.println("The maximum numeric value in above string is: " + maxNum); } }
Output
The string is: 123abc874def235ijk999 The maximum numeric value in above string is: 999
Now let us understand the above program.
First, the string is displayed. Then, regular expression is created for at least one digit. Then regex is compiled and matcher object is created. The code snippet that demonstrates this is given as follows.
String str = "123abc874def235ijk999"; System.out.println("The string is: " + str); String regex = "\d+"; Pattern ptrn = Pattern.compile(regex); Matcher match = ptrn.matcher(str);
A while loop is used to find the maximum numeric value in the string. Then maxNum is displayed. The code snippet that demonstrates this is given as follows −
int maxNum = 0; while(match.find()) { int num = Integer.parseInt(match.group()); if(num > maxNum) { maxNum = num; } } System.out.println("The maximum numeric value in above string is: " + maxNum);
Advertisements