
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
Use the Quantifier in Java Regular Expressions
In general, the ? quantifier represents 0 or 1 occurrences of the specified pattern. For example - X? means 0 or 1 occurrences of X.
The regex "t.+?m" is used to find the match in the string "tom and tim are best friends" using the ? quantifier.
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[]) { Pattern p = Pattern.compile("t.+?m"); Matcher m = p.matcher("tom and tim are best friends"); System.out.println("The input string is: tom and tim are best friends"); System.out.println("The Regex is: t.+?m"); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); } } }
Output
The input string is: tom and tim are best friends The Regex is: t.+?m Match: tom Match: tim
Now let us understand the above program.
The subsequence “t.+?m” is searched in the string sequence "tom and tim are best friends". The find() method is used to find if the subsequence i.e. t followed by any number of t and ending with m is in the input sequence and the required result is printed.
Advertisements