Reluctant quantifiers Java Regular expressions



Greedy quantifiers are the default quantifiers. A greedy quantifier matches as much as possible from the input string (longest match possible) if match not occurred it leaves the last character and matches again.

Whereas a reluctant or, non-greedy quantifier matches as little as possible, initially the non-greedy quantifier matches the first character if match not occurred it adds another character from the input string and tries to match.

If you place a "?" after a greedy quantifier it becomes reluctant or non-greedy quantifier. Following is the list of reluctant quantifiers −

Quantifier Description
re*? Matches zero or more occurrences.
re?? Matches zero or, 1 occurrence.
re+? Matches one or more occurrences.
re{n}? Matches exactly n occurrences.
re{n, }? Matches at least n occurrences.
re{n, m}? Matches at least n and at most m occurrences.

Example

 Live Demo

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test {    public static void main(String[] args) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter input text: ");       String input = sc.nextLine();       String regex = "[0-9]+?";       //Creating a pattern object       Pattern pattern = Pattern.compile(regex);       //Matching the compiled pattern in the String       Matcher matcher = pattern.matcher(input);       while (matcher.find()) {          System.out.print("Pattern found from " + matcher.start()+ " to " + (matcher.end()-1)+"::");          System.out.print(matcher.group());          System.out.println();       }    } }

Output

Enter input text: 12345678 Pattern found from 0 to 0::1 Pattern found from 1 to 1::2 Pattern found from 2 to 2::3 Pattern found from 3 to 3::4 Pattern found from 4 to 4::5 Pattern found from 5 to 5::6 Pattern found from 6 to 6::7 Pattern found from 7 to 7::8
Updated on: 2020-01-13T05:53:17+05:30

967 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements