2014-04-03 87 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());  
}