貪婪限定符 Java 正則表示式中的 java。
貪婪限定符是預設限定符。當匹配未發生時,貪婪限定符將盡可能多地匹配輸入字串(儘可能最長的匹配),它會跳過最後一個字元並再次匹配。以下是貪婪限定符的列表 -
| 限定符 | 說明 |
|---|---|
| re* | 匹配零次或多次出現。 |
| re? | 匹配零次或一次出現。 |
| re+ | 匹配一次或多次出現。 |
| re{n} | 精確匹配 n 次出現。 |
| re{n, } | 至少匹配 n 次。 |
| re{n, m} | 至少匹配 n 次,最多匹配 m 次。 |
示例
在以下 Java 示例中,我們嘗試匹配 1 個或多個數字,我們的輸入字串為 45545,雖然值 4、45、455 等符合條件,但我們正在使用貪婪限定符,它匹配最長可能。
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());
}
}
}輸出
Enter input text: Matched text: 45545
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP