
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Greedy Qualifier in Java Regular Expressions
A greedy qualifier repeats the specified token as many times as possible and then the engine backtracks and the greedy qualifier gives up matches to eventually find the required match.
The regex "(\w+)(\d)(\w+)" is used to find the match in the string "EarthHas1Moon".
A program that demonstrates this is given as follows:
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { String str = "EarthHas1Moon"; String regex = "(\w+)(\d)(\w+)"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); m.find(); System.out.println(m.group(1)); System.out.println(m.group(2)); System.out.println(m.group(3)); } }
Output
EarthHas 1 Moon
Now let us understand the above program.
The regex is “(\w+)(\d)(\w+)”. This is searched in the string sequence "EarthHas1Moon". The find() method is used to find if the regex is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:
String str = "EarthHas1Moon"; String regex = "(\w+)(\d)(\w+)"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); m.find(); System.out.println(m.group(1)); System.out.println(m.group(2)); System.out.println(m.group(3));
Advertisements