簡體   English   中英

正則表達式示例

[英]Regular Expressions example

我對這個例子有點困惑......我不明白這個String模式中寫的是什么。 還有, find什么? 我是從TutorialsPoint學習的。

拜托,任何人都可以幫我理解嗎?

碼:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {
    public static void main(String args[]) {

        // String to be scanned to find the pattern.
        String line = "This order was placed for QT3000! OK?";
        String pattern = "(.*)(\\d+)(.*)";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        if (m.find()) {
            System.out.println("Found value: " + m.group(0));
            System.out.println("Found value: " + m.group(1));
            System.out.println("Found value: " + m.group(2));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

輸出:

發現價值:此訂單是為QT3000下達的! 好?
發現價值:此訂單是為QT300下達的
發現價值:0

該模式有3個捕獲組

  • (.*)表示任何字符為零或更多(Capture group 1)
  • (\\\\d+)一個或多個數字(捕獲組2)
  • (.*)表示任何字符為零或更多(Capture group 3)

當調用find() ,它“嘗試查找與模式匹配的輸入序列的下一個子序列。” Matcher.Find()

當你調用這些行時:

System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
  • m.group(0)表示正則表達式評估的整個String
  • m.group(1)指捕獲組1(任何字符的零個或多個)
  • m.group(2)指捕獲組2(一個或多個數字)
  • 您當前沒有輸出捕獲組3(任何字符的零個或多個)

您將看到m.group(1)返回This order was placed for QT300 ,而最后一個零則留給m.group(2)因為捕獲組2必須至少有1位數。

如果要將捕獲組3( m.group(3) )添加到輸出,它將顯示m.group(2)的最后一個零之后的剩余字符串。

換一種說法:

System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
System.out.println("Found value: " + m.group(3));

會顯示:

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0
Found value: ! OK?

希望這可以幫助!

find()將找到與模式匹配的輸入序列的下一個子序列。 當且僅當輸入序列的子序列與此匹配器的模式匹配時,才返回true

你的正則表達式有3組: (.*)是第1組, (\\\\d+)是第2組, (.*)是第3組。

第1組匹配前面標記的0或更多,除了換行符之外的任何字符。

第2組與前面的標記中的1個或多個匹配任何數字字符(0-9)。

第3組與第1組相同。

所以當你的電話:

m.group(0)將返回整個String。

m.group(1)將返回第1組。

m.group(2)將返回第2組。

傳遞給組的參數是正則表達式中的組索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM