Home > Java > javaTutorial > Java regular expressions with quantifiers

Java regular expressions with quantifiers

王林
Release: 2023-08-22 09:57:02
forward
599 people have browsed it

拥有量词 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();
      }
   }
}
Copy after login

Output

Enter input text:
45678
45678
Copy after login

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!

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