- Trending Categories
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
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.
- Related Articles
- Use a character class in Java Regular Expressions
- Use a quantifier to find a match in Java
- Java Regular Expressions Tutorial
- Reset the Matcher in Java Regular Expressions
- Greedy quantifiers Java Regular expressions in java.
- Back references in Java regular expressions
- Regular Expressions syntax in Java Regex
- Regex quantifiers in Java Regular Expressions
- Matcher.pattern() method in Java Regular Expressions
- Pattern.matches() method in Java Regular Expressions
- Explain quantifiers in Java regular expressions
- Explain the sub-expression "[...]" in Java Regular expressions
- Explain the Metacharacter "B" in Java Regular Expressions.
- Java regular expressions sample examples
- Possessive quantifiers Java Regular expressions

Advertisements