簡體   English   中英

正則表達式(正則表達式)模式匹配

[英]Regular Expressions (regex) Pattern Matching

有人可以幫我理解這個程序如何計算下面給出的輸出?

import java.util.regex.*;
class Demo{
    public static void main(String args[]) {
        String name = "abc0x12bxab0X123dpabcq0x3423arcbae0xgfaaagrbcc";

        Pattern p = Pattern.compile("[a-c][abc][bca]");
        Matcher m = p.matcher(name);

        while(m.find()) {
            System.out.println(m.start()+"\t"+m.group());       
        }
    }
}

輸出:

0   abc
18  abc
30  cba
38  aaa
43  bcc

讓我們分析:
"[ac][abc][bca]"

此模式查找每組3個字母的組。

[ac]表示首字母必須在ac之間,因此它可以是abc

[abc]表示第二個字母必須是以下字母abc a基本上[ac]

[bca] bca [bca]意思是第三個字母必須是bca ,這里的命令並不重要。

您需要知道的所有內容都在官方的java正則表達式教程中http://docs.oracle.com/javase/tutorial/essential/regex/

它只是根據"[ac][abc][bca]"指定的規則在String搜索匹配項

0   abc  --> At position 0, there is [abc].
18  abc  --> Exact same thing but at position 18.
30  cba  --> At position 30, there is a group of a, b and c (specified by [a-c])
38  aaa  --> same as 30
43  bcc  --> same as 30

請注意,計數從0開始。所以第一個字母位於第0位,第二個字母位於第1位,依此類推......

有關Regex及其使用的更多信息,請參閱: Regex的Oracle教程

此模式基本上匹配3個字符的單詞,其中每個字母是abc

然后它打印出每個匹配的3-char序列以及找到它的索引。

希望有所幫助。

它打印出字符串中的位置,從0開始而不是1,其中發生每個匹配。 這是第一場比賽,“abc”發生在第0位。第二場比賽“abc”發生在第18位。

基本上它匹配任何包含'a','b'和'c'的3個字符串。

模式可以寫成“[ac] {3}”,你應該得到相同的結果。

讓我們看一下你的源代碼,因為regexp本身已經在其他答案中得到了很好的解釋。

//compiles a regexp pattern, kind of make it useable
Pattern p = Pattern.compile("[a-c][abc][bca]");

//creates a matcher for your regexp pattern. This one is used to find this regexp pattern
//in your actual string name.
Matcher m = p.matcher(name);

//loop while the matcher finds a next substring in name that matches your pattern
while(m.find()) {
    //print out the index of the found substring and the substring itself
    System.out.println(m.start()+"\t"+m.group());       
}

暫無
暫無

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

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