Home  >  Article  >  Java  >  Java regular expressions with quantifiers

Java regular expressions with quantifiers

王林
王林forward
2023-08-22 09:57:02589browse

拥有量词 Java 正则表达式

The greedy quantifier is the default quantifier. The greedy quantifier matches as much as possible in the input string (longest match), and if there is no match, keeps the last character and matches again.

The possessive quantifier is similar to the greedy quantifier, the only difference is that it initially tries to match as many characters as possible, and does not backtrack like the greedy quantifier if there is no match.

If you add " " after the greedy quantifier, it becomes a possessive quantifier. The following is a list of possessive quantifiers:

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

Example

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(matcher.group());
         System.out.println();
      }
   }
}

Output

Enter input text:
45678
45678

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

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete