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

 Live Demo

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.

Updated on: 2019-07-30T22:30:24+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements