正则表达式:组与模式标记
前言??终于又把看了不到一半的【java编程思想】重新拾起,但是遗憾的是前面的内容也是不记得什么了,所以为了以后能记得我看过的内容,还是随手写下这些知识点吧,方便以后查看。 正文??今天要说明的是正则表达式中组和模式标记的内容。因为在课堂学习的内容中并没有这方面的知识,对我来说算是一个新知识点吧。 ??这个表达式中有三个组,组0是ABCD,组1是BC,组2是C ??我们来看下面的例子:–来自【java编程思想】 public class Example {
public static void main(String[] args) {
final String POEM = "Twas brillig,and the slithy tovesn"+
"Did gyre and gimble in the wabe.n"+
"All mimsy were the borogoves,n"+
"And the mome raths outgrabe.nn"+
"Beware the Jabberwock,my son,n"+
"The jaws that bite,the claws that catch.n"+
"Beware the Jubjub bird and shunn"+
"The frumious Bandersnatch.";
Matcher m = Pattern.compile("(?m)(S+)s+((S+)s+(S+))$").matcher(POEM);
while(m.find()){
for(int j=0;j<=m.groupCount();j++){
System.out.print("["+m.group(j)+"]");
}
System.out.println();
}
}
}
??下面是输出结果: [the slithy toves][the][slithy toves][slithy][toves]
[in the wabe.][in][the wabe.][the][wabe.]
[were the borogoves,][were][the borogoves,][the][borogoves,]
[mome raths outgrabe.][mome][raths outgrabe.][raths][outgrabe.]
[the Jabberwock,][the][Jabberwock,][Jabberwock,my][son,]
[claws that catch.][claws][that catch.][that][catch.]
[bird and shun][bird][and shun][and][shun]
[The frumious Bandersnatch.][The][frumious Bandersnatch.][frumious][Bandersnatch.]
??就代码来说,我刚开始就有看不懂的地方了,(?m)是个什么东西,$又是什么东西?带着这样的问题就引出了模式标记的内容。
??其余的常量我就不一一列举了,在上面的程序中我们用到了(?m),原来它是多行模式,$表示的是在结束符的末尾匹配,这样我大概就可以看懂程序了。 ??(?m)(S+)s+((S+)s+(S+))$这个正则表达式的匹配的就是从每行的最后三个单词,S和s表示意义我就不说了。 ??A表示每行最后三个单词的第一个为组1,BC为组2,B为组3,C为组4。这样就对输出结果没有任何疑问了。 ??下面我再给出一个用^标记的例子。 String str = "java has regexnJava has regexn"+
"JAVA has pretty good regular expresstionsn"+
"Regular expresstions are in Java";
Pattern p = Pattern.compile("^java",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group());
}
??下面是输出结果: java Java JAVA ??”^“表示从一行的开始进行匹配,也就是说“^java”是所有以java开头都可以被匹配到。因为在这个例子中用到了Pattern.CASE_INSENSITIVE这个模式,忽略大小写,所以Java,JAVA也都可以被匹配到。 小结??正则表达式的内容果真是无穷丰富,以前只是能从一段字符串中匹配数字而已,虽然现在也没啥进步/(ㄒoㄒ)/~~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |