Home > Java > javaTutorial > Application of greedy quantifier in Java regular expressions

Application of greedy quantifier in Java regular expressions

WBOY
Release: 2023-08-19 11:41:20
forward
891 people have browsed it

Application of greedy quantifier in Java regular expressions

The greedy quantifier is the default quantifier. If no match occurs, the greedy quantifier tries to match as much as possible from the input string (the longest match), and if a match fails it keeps the last character and tries again. The following is a list of greedy quantifiers:

Quantifier Description
re* Matches zero or more occurrences.

re? Matches zero or one occurrences.

re Matches one or more occurrences.

re{n} Exactly matches n occurrences.

re{n, } Match at least n occurrences.

re{n, m} Match at least n and at most m occurrences.

Example

In the following Java example, we are trying to match one or more numbers, our input string is 45545, although the values ​​4, 45, 455, etc. are all eligible, but because we use a greedy quantifier, it will match the longest possible value.

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);
      System.out.println(“”Matched text: );
      while (matcher.find()) {
         System.out.println(matcher.group());
      }
   }
}
Copy after login

Output

Enter input text:
Matched text:
45545
Copy after login

The above is the detailed content of Application of greedy quantifier in Java regular expressions. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template