2014-04-03 84 views
0

有人可以幫我理解這個程序如何計算下面給出的輸出嗎?正則表達式(正則表達式)模式匹配

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());  
     } 
    } 
} 

OUTPUT:

0 abc 
18 abc 
30 cba 
38 aaa 
43 bcc 

回答

1

它簡單地根據通過"[a-c][abc][bca]"

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 

通知指定的規則的匹配搜索String,計數從0開始。因此,第一個字母是在位置0,第二IST在位置1處等等...

更多信息有關正則表達式,它的用途看:Oracle Tutorial for Regex

1

讓analize:
"[a-c][abc][bca]"

這種模式看重的是每3個字母組。

[a-c]意味着第一個字母必須是ac之間,以便它可以是abc

[abc]意味着第二個字母必須是下列字母之一abc共basicly [a-c]

[bca]意思是第三個字母必須是bca,order rathe r在這裏無關緊要。

一切你需要知道什麼是官方Java正則表達式教程 http://docs.oracle.com/javase/tutorial/essential/regex/

0

這種模式基本匹配3個字符的話,其中每個字母或者是ab,或c

然後打印出每個匹配的3個字符序列以及找到它的索引。

希望有所幫助。

0

它打印出字符串中的位置,從0開始,而不是從1開始,每個匹配發生的位置爲1。這是第一個匹配,「abc」發生在位置0.第二個匹配「abc」發生在字符串位置18.

實質上它匹配任何包含'a','b'的任何3個字符的字符串, 'C'。

該模式可以寫成「[a-c] {3}」,你應該得到相同的結果。

0

讓我們來看看你的源代碼,因爲正則表達式本身已經在其他答案中得到了很好的解釋。

//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());  
}