不情願量詞 Java 正則表示式
貪婪量詞是預設的量詞。在輸入字串中,貪婪量詞儘可能地匹配(最長的匹配),如果未匹配,則跳過最後一個字元並再次匹配。
而不情願或非貪婪量詞儘可能少的匹配,最初,非貪婪量詞匹配第一個字元,如果未匹配,則從輸入字串中新增另一個字元並嘗試匹配。
如果在貪婪量詞後面加上 “?”,它將變為不情願或非貪婪量詞。以下是所列不情願量詞列表 -
量詞 | 說明 |
---|---|
re*? | 匹配零個或多個項。 |
re?? | 匹配零或 1 個項。 |
re+? | 匹配一個或多個項。 |
re{n}? | 精確匹配 n 個項。 |
re{n, }? | 至少匹配 n 個項。 |
re{n, m}? | 至少匹配 n 個且最多匹配 m 個項。 |
示例
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(); } } }
輸出
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
廣告