欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java正则表达式彻底研究

程序员文章站 2022-05-19 11:16:25
 package testreg; import java.util.regex.matcher; import java.util...
 package testreg;
import java.util.regex.matcher;
import java.util.regex.pattern;

/**
* <p>title: 正则表达式的研究</p>
* <p>description:
* 最近在工作中常常用到一些正则表达式的使用问题,到网上去找介绍大多是一鳞半爪。求人不如
* 求已。一狠心,自己看!这两天利用我们项目两期之间的一点空闲对j2se所支持的正则表达式来
* 了个彻底研究!代价是……就是浪废了部门近十二张白纸。闲话少说,书归正传。
* 原理:
*     正则表达式的原理是有限状态自动机,自动机内部有有限个状态,有一个初始状态,有一个
* 结束状态。自动机根据输入和自身内部的当前状态来决定下一步于什么。呵呵,这是很久以前学
* 的东东了也记不清了,大家只作参照吧。
* java中的正则表达式:
*     从j2se1.4起java增加了对正则表达式的支持就是java.util.regex包,这个包中主要有
* 3个类:pattern,代表模式,就是正则表达式自身,matcher,是一个有限状态自动机,其实大多
* 数的活还是让pattern类于了,matcher往往只是简单的调用pattern,不知道这是什么模式。这
* 两个类写的都很经典,还有不少算法在内值得有功力的人仔细研究一下。另一个是一个异常类当所
* 用正则表达式不正确时抛出,是运行时异常。
* 几个难点:
*   1.line terminator
*     line terminator 中文意终结符,是指一个或两个字符组成的字符序列。java中的
*     所有line terminator:
*     a newline (line feed) character ('\n'),
*      -----------换行符(0a)
*     a carriage-return character followed immediately by a newline character ("\r\n"),
*      -----------回车+换行(0d0a)
*     a standalone carriage-return character ('\r'),
*      -----------回车(0d)
*     a next-line character ('\u0085'),
*      ------------下一行符?(?表示我也不知道是什么,请大家明白的给我发mail
*     a line-separator character ('\u2028'), or
*      ------------行分隔符?
*     a paragraph-separator character ('\u2029).
*      ------------段落分隔符?
*      if unix_lines mode is activated, then the only line terminators recognized are newline characters.
*      如果使用unix模式则只有\n被认为是line terminator,也就是在使用pattern时如下:
*      pattern p=pattern.compile("正则表达式",pattern.unix_line);
*      或 pattern p=pattern.compile("(?d)正则表达式")
*      "."匹配除line terminator以外的所有字符(未指定dotall时)
*      在指定dotall模式时"."匹配所有字符
*   2.quantifiers,greedy,reluctant and possessive.
*     这几个词不太好译,原文是greedy quantifiers,reluctant quantifiers and possessive
*     quantifiers凭我这点英语我只好译作贪婪的量子,不情愿的量子和占有欲强的量子?这也太搞笑了,
*     好在我理解了他们的意思。这点等下我细说。
*   3. 对于[a-za-z],[a-d[h-i]],[^a-f],[b-f&&[a-z]],[b-f&&[^cd]]等形式的理解
*     对于上述,原文用range,union,negation,intersection,subtraction等来描述
*     range表是范围,union是并集,negation是取反,intersection是交集,subtraction
*     是……是减法??反正是减去一部分的意思
*     range       a-z 从a到z的小写字母
*     negation    [^a-f]除了a-f之外所有的,全集是所有字符
*     union       [a-d[h-i]] a-d并h-i
*     subtraction [b-f&&[^cd]] 就是b-f中除了cd以外的都是
*     intersection[b-f&&[a-z]] 就是b-f与a-z中的公共部分
*     我总结了一下,其实就是方括号表示一个集合,集合中的元素用列举法表示如[abcd],但太多
*     了怎么为?总不能把从a到z的全列举吧?那就用a-z表示且省略了方括号,交集用&&表示,并集
*     省略,差集(对subtraction译成差集还差不多)用交集和取反来表示。所以,以上的可表示为:
*     [[a-z][a-z]],[[a-d][h-i]],[^a-f],[[b-f]&&[a-z]],[[b-f]&&[^cd]]
*     这样是不是和我们的习惯相符了.
*   4.各个标志的意义
*     在生成pattern时可以同时使用几个标志来指定进行匹配时的方案。
*     用法形如:pattern p=pattern.compile(".*a?",pattern.unix_lines);
*     当同时指定多个标志时可以使用"|"操作符连接如:
*     pattern p=pattern.compile(".*a?,pattern.unix_lines|pattern.dotall);
*     也可以在表达式中指定如:
*     pattern p=pattern.compile("(?d).*a?");
*     pattern p=pattern.compile("(?d)(?s).*a?");
*     以上两个定义和前面两个对应等价
*     所有的标志如下:
*     constant               equivalent embedded flag expression 
     pattern.canon_eq              none enables canonical equivalence
     pattern.case_insensitive      (?i) enables case-insensitive matching
     pattern.comments              (?x) permits whitespace and comments in pattern.
     pattern.multiline             (?m) enables multiline mode.
     pattern.doatall               (?s) enables dotall mode
     pattern.unicode_case          (?u) enables unicode-aware case folding.
     pattern.unix_lines            (?d) enables unix lines mode

     canon_eq 指定使用规范等价模式?这个我理解的也有限,是不是说只要指定了这个模式则
     ascii码的'a'就可以和unicode的'a'还有xxx码的'a'相等?请教各位。(mail to me)

     case_insensitive 指定使用大小写不敏感的匹配模式,这个好理解,但要注意这个标志只是
     对ascii码有效,要使unicode在比较时也忽略大小写要同时指定unicode_case,就是要指定
     case_insensitive|unicode_case或使用(?i)(?u)

     comments 指定使用注释和忽略空白,也就是".*a"==".  *a #this is comments"我想这个
*     在正则表达式很大,而且是在文件中输入时比较有用,平时我看也用不上。
*     
*     multiline in multiline mode the expressions ^ and $ match just after 
*     or just before, respectively, a line terminator or the end of the 
*     input sequence. by default these expressions only match at the beginning 
*     and the end of the entire input sequence
*     指定使用多行匹配模式,在默认模式下,^和$分别只匹配一个输入的开始和结束。
*     在这种模式下,^和$ 除了匹配整个输入的开始和结束外还匹配一个line terminator的后边和
*     前边(不是前边和后边,就是说^匹配line terminator的后边$匹配line terminator的前边。
*     
*     doatall 如指定了这个模式则"."可匹配任何字符包括line terminator
*     
*     unix_lines 指定这个模式时只有\n被认为是line terminator而\r和\r\n都不是

*  其他的我一时想不起来了,在具体介绍时再说吧。
* </p>
*/
public class testreg2
{

   public static void main(string[] args)
   {
       string str1 = "";
       object str = "";
       //注意:\r,\n,\b等转义字符在java字符串常量中要写成\\r,\\n,\\b等,否则编译都过不去
       //\s匹配\r,\n,\r和空格
       system.out.println("\\s匹配\\r,\\n,\\r和空格 "+" \t\n\r".matches("\\s{4}"));
       //\s和\s互逆
       system.out.println("\\s和\\s互逆 "+"/".matches("\\s"));
       //.不匹配\r和\n
       system.out.println(".不匹配\\r和\\n "+"\r".matches("."));
       system.out.println("\n".matches("."));

       //\w匹配字母,数字和下划线
       system.out.println("\\w匹配字母,数字和下划线  "+"a8_".matches("\\w\\w\\w"));
       //\w和\w互逆
       system.out.println("\\w和\\w互逆 "+"&_".matches("\\w\\w"));
       //\d匹配数字
       system.out.println("\\d匹配数字 "+"8".matches("\\d"));
       //\d与\d互逆
       system.out.println("\\d与\\d互逆"+"%".matches("\\d"));
       //两者都匹配但意文不同
       system.out.println("======================");
       system.out.println("表示\\000a匹配\\000a "+"\n".matches("\n"));
       system.out.println("表示\\n匹配换行 "+"\n".matches("\\n"));
       system.out.println("======================");
       //两者都匹配但意文不同
       system.out.println("\r".matches("\r"));
       system.out.println("\r".matches("\\r"));
       system.out.println("======================");
       //^匹配开头
       system.out.println("^匹配开头"+"hell".matches("^hell"));
       system.out.println("abc\nhell".matches("^hell"));
       //$匹配结束
       system.out.println("$匹配结束"+"my car\nabc".matches(".*ar$"));
       system.out.println("my car".matches(".*ar$"));
       //\b匹配界
       system.out.println("\\b匹配界 "+"bomb".matches("\\bbom."));
       system.out.println("bomb".matches(".*mb\\b"));
       //\b与\b互逆
       system.out.println("\\b与\\b互逆"+"abc".matches("\\babc"));

       //[a-z]匹配a到z的小写字母
       system.out.println("[a-z]匹配a到z的小写字母"+"s".matches("[a-z]"));
       system.out.println("s".matches("[a-z]"));
       system.out.println("9".matches("[0-9]"));

       //取反
       system.out.println("取反"+"s".matches("[^a-z]"));
       system.out.println("s".matches("[^a-z]"));
       system.out.println("9".matches("[^0-9]"));

       //括号的作用
       system.out.println("括号的作用"+"ab9".matches("[a-z][a-z][0-9]"));
       system.out.println("ab9bc6".matches("([a-z][a-z][0-9])+"));
       //或运算
       system.out.println("或运算"+"two".matches("two|to|2"));
       system.out.println("to".matches("two|to|2"));
       system.out.println("2".matches("two|to|2"));

       //[a-za-z]==[a-z]|[a-z]
       system.out.println("[a-za-z]==[a-z]|[a-z]"+"a".matches("[a-za-z]"));
       system.out.println("a".matches("[a-za-z]"));
       system.out.println("a".matches("[a-z]|[a-z]"));
       system.out.println("a".matches("[a-z]|[a-z]"));

       //体会一下以下四个
       system.out.println("体会一下以下四个\n==========================");
       system.out.println(")".matches("[a-za-z)]"));
       system.out.println(")".matches("[a-za-z)_-]"));
       system.out.println("_".matches("[a-za-z)_-]"));
       system.out.println("-".matches("[a-za-z)_-]"));
       system.out.println("==========================");
       system.out.println("b".matches("[abc]"));
       //[a-d[f-h]]==[a-df-h]
       system.out.println("[a-d[f-h]]==[a-df-h]"+"h".matches("[a-d[f-h]]"));
       system.out.println("a".matches("[a-z&&[def]]"));
       //取交集
       system.out.println("取交集"+"a".matches("[a-z&&[def]]"));
       system.out.println("b".matches("[[a-z]&&[e]]"));
       //取并
       system.out.println("取并"+"9".matches("[[a-c][0-9]]"));
       //[a-z&&[^bc]]==[ad-z]
       system.out.println("[a-z&&[^bc]]==[ad-z]"+"b".matches("[a-z&&[^bc]]"));
       system.out.println("d".matches("[a-z&&[^bc]]"));
       //[a-z&&[^m-p]]==[a-lq-z]
       system.out.println("[a-z&&[^m-p]]==[a-lq-z]"+"d".matches("[a-z&&[^m-p]]"));
       system.out.println("a".matches("\\p{lower}"));
       ///注意以下体会\b的用法(注意,在字符串常量中十目直接写\b表退格,所以要写\\b
       system.out.println("*********************************");
       system.out.println("aawordaa".matches(".*\\bword\\b.*"));
       system.out.println("a word a".matches(".*\\bword\\b.*"));
       system.out.println("aawordaa".matches(".*\\bword\\b.*"));
       system.out.println("a word a".matches(".*\\bword\\b.*"));
       system.out.println("a word a".matches(".*word.*"));
       system.out.println("aawordaa".matches(".*word.*"));
       //体会一下组的用法
       //组的顺序,只数"("第一个为第一组第二个是第二组……
       //第0组表示整个表达式
       system.out.println("**************test group**************");
       pattern p = pattern.compile("(([abc]+)([123]+))([-_%]+)");
       matcher m = p.matcher("aac212-%%");
       system.out.println(m.matches());
       m = p.matcher("cccc2223%_%_-");
       system.out.println(m.matches());
       system.out.println("======test group======");
       system.out.println(m.group());
       system.out.println(m.group(0));
       system.out.println(m.group(1));
       system.out.println(m.group(2));
       system.out.println(m.group(3));
       system.out.println(m.group(4));
       system.out.println(m.groupcount());
       system.out.println("========test end()=========");
       system.out.println(m.end());
       system.out.println(m.end(2));
       system.out.println("==========test start()==========");
       system.out.println(m.start());
       system.out.println(m.start(2));
       //test backslash测试反向引用?
       pattern pp1=pattern.compile("(\\d)\\1");//这个表达式表示必须有两相同的数字出现
       //\1表示引用第一个组\n表示引用第n个组(必须用\\1而不能用\1因\1在字符串中另有意义(我也知道是什么)
       matcher mm1=pp1.matcher("3345");//33匹配但45不匹配
       system.out.println("test backslash测试反向引用");
       system.out.println(mm1.find());
       system.out.println(mm1.find());

       //体会以下不同
       system.out.println("==============test find()=========");
       system.out.println(m.find());
       system.out.println(m.find(2));

       system.out.println("这是从第三个字符(index=2)开始找的group结果");
       system.out.println(m.group());
       system.out.println(m.group(0));
       system.out.println(m.group(1));
       system.out.println(m.group(2));
       system.out.println(m.group(3));
       m.reset();
       system.out.println(m.find());
       //测试一个模式可多次匹配一个串
       system.out.println("测试一个模式可多次匹配一个串");
       pattern p1 = pattern.compile("a{2}");
       matcher m1 = p1.matcher("aaaaaa");
       //这说明matcher的matchs()方法是对事个字符串的匹配,
       system.out.println(m1.matches());
       system.out.println(m1.find());
       system.out.println(m1.find());
       system.out.println(m1.find());
       system.out.println(m1.find());
       //再测试matchs()
       system.out.println("再测试matchs()");
       pattern p2 = pattern.compile("(a{2})*");
       matcher m2 = p2.matcher("aaaa");
       system.out.println(m2.matches());
       system.out.println(m2.matches());
       system.out.println(m2.matches());
       //所以find是在一个串中找有没有对应的模式,而matchs是完全匹配
       //test lookupat()
       system.out.println("test lookupat()");
       pattern p3 = pattern.compile("a{2}");
       matcher m3 = p3.matcher("aaaa");
       system.out.println(p3.flags());
       system.out.println(m3.lookingat());
       system.out.println(m3.lookingat());
       system.out.println(m3.lookingat());
       //总结以上matchs()是整个匹配且总是从头开始,find是部分匹配且从上一次匹配结束时开始找
       //lookingat也是从头开始,但是部分匹配
       system.out.println("======test 空白行========");
       system.out.println("         \n".matches("^[ \\t]*$\\n"));

       //演示appendxxx的用法
       system.out.println("=================test append====================");
       pattern p4 = pattern.compile("cat");
       matcher m4 = p4.matcher("one cat two cats in the yard");
       stringbuffer sb = new stringbuffer();
       boolean result = m4.find();
       int i=0;
       system.out.println("one cat two cats in the yard");
       while(result)
       {m4.appendreplacement(sb, "dog");
       system.out.println(m4.group());
       system.out.println("第"+i+++"次:"+sb.tostring());
       result = m4.find();
       }
       system.out.println(sb.tostring());
       m4.appendtail(sb);
       system.out.println(sb.tostring());

       //test unix_lines
       system.out.println("test unix_lines");
       pattern p5=pattern.compile(".",pattern.unix_lines);
       matcher m5=p5.matcher("\n\r");
       system.out.println(m5.find());
       system.out.println(m5.find());

       //test unix_lines
       system.out.println("test unix_lines");
       pattern p6=pattern.compile("(?d).");
       matcher m6=p6.matcher("\n\r");
       system.out.println(m6.find());
       system.out.println(m6.find());

       //test unix_lines
       system.out.println("test unix_lines");
       pattern p7=pattern.compile(".");
       matcher m7=p7.matcher("\n\r");
       system.out.println(m7.find());
       system.out.println(m7.find());

       //test case_insensitive
       system.out.println("test case_insensitive");
       pattern p8=pattern.compile("a",pattern.case_insensitive);
       matcher m8=p8.matcher("aa");
       system.out.println(m8.find());
       system.out.println(m8.find());
       system.out.println("test case_insensitive");
       pattern p9=pattern.compile("(?i)a");
       matcher m9=p9.matcher("aa");
       system.out.println(m9.find());
       system.out.println(m9.find());
       system.out.println("test case_insensitive");
       pattern p10=pattern.compile("a");
       matcher m10=p10.matcher("aa");
       system.out.println(m10.find());
       system.out.println(m10.find());

       //test comments
       system.out.println("test comments");
       pattern p11=pattern.compile(" a a #ccc",pattern.comments);
       matcher m11=p11.matcher("aa a a #ccc");
       system.out.println(m11.find());
       system.out.println(m11.find());
       system.out.println("test comments");
       pattern p12 = pattern.compile("(?x) a a #ccc");
       matcher m12 = p12.matcher("aa a a #ccc");
       system.out.println(m12.find());
       system.out.println(m12.find());

       //test multiline这个大家多试试参照我上面对多行模式的理解
       system.out.println("test multiline");
       pattern p13=pattern.compile("^.?",pattern.multiline|pattern.dotall);
       matcher m13=p13.matcher("helloohelloo,loveroo");
       system.out.println(m13.find());
       system.out.println("start:"+m13.start()+"end:"+m13.end());
       system.out.println(m13.find());
       //system.out.println("start:"+m13.start()+"end:"+m13.end());
       system.out.println("test multiline");
       pattern p14=pattern.compile("(?m)^hell.*oo$",pattern.dotall);
       matcher m14=p14.matcher("hello,worldoo\nhello,loveroo");
       system.out.println(m14.find());
       system.out.println("start:"+m14.start()+"end:"+m14.end());
       system.out.println(m14.find());
       //system.out.println("start:"+m14.start()+"end:"+m14.end());
       system.out.println("test multiline");
       pattern p15=pattern.compile("^hell(.|[^.])*oo$");
       matcher m15=p15.matcher("hello,worldoo\nhello,loveroo");
       system.out.println(m15.find());
       system.out.println("start:"+m15.start()+"end:"+m15.end());
       system.out.println(m15.find());
      // system.out.println("start:"+m15.start()+"end:"+m15.end());

       //test dotall
       system.out.println("test dotall");
       pattern p16=pattern.compile(".",pattern.dotall);
       matcher m16=p16.matcher("\n\r");
       system.out.println(m16.find());
       system.out.println(m16.find());

       system.out.println("test dotall");
       pattern p17=pattern.compile(".");
       matcher m17=p17.matcher("\n\r");
       system.out.println(m17.find());
       system.out.println(m17.find());

       system.out.println("test dotall");
       pattern p18=pattern.compile("(?s).");
       matcher m18=p18.matcher("\n\r");
       system.out.println(m18.find());
       system.out.println(m18.find());

       //test canon_eq这个是jdk的例子但我实在不明白是什么意思,向大家请教
       system.out.println("test canon_eq");
       pattern p19=pattern.compile("a\u030a",pattern.canon_eq);
       system.out.println(character.gettype('\u030a'));
       system.out.println("is"+character.isisocontrol('\u030a'));
       system.out.println("is"+character.isunicodeidentifierpart('\u030a'));
       system.out.println(character.gettype('\u00e5'));
       system.out.println("is"+character.isisocontrol('\u00e5'));
       matcher m19=p19.matcher("\u00e5");
       system.out.println(m19.matches());
       system.out.println(character.gettype('\u0085'));
       system.out.println("is"+character.isisocontrol('\u0085'));

      //注意下面三个例子体会greedy,reluctant and possessive quantifiers的不同
       pattern ppp=pattern.compile(".*foo");
       matcher mmm=ppp.matcher("xfooxxxxxxfoo");
       /**
        * greedy   quantifiers 
           x?      x, once or not at all 
           x*      x, zero or more times 
           x+      x, one or more times 
           x{n}    x, exactly n times 
           x(n,}   x, at least n times 
           x{n,m}  x, at least n but not more than m times 
           greedy quantifiers是最常用的一种,如上,它的匹配方式是先匹配尽可能多的字符,当
           这样造成整个表达式整体不能匹配时就退一个字符再试比如:
           .*foo与xfooxxxxxxfoo的匹配过程,.*先与整个输入匹配,发现这样不行,整个串不能匹配
        *  于是退最后一个字符"o"再试,还不行,再退直到把foo都退出才发现匹配于是结束。因为这个过程
        *  总是先从最大匹配开始到找到一个匹配,所以.*与之匹配的总是一个最大的,这个特点和资本家相似
        *  故名贪婪的
        */
       boolean isend=false;
       int k=0;
       system.out.println("==========");
       system.out.println("xfooxxxxxxfoo");
       while(isend==false)
       try{
           system.out.println("the:"+k++);
           system.out.println(mmm.find());
           system.out.println(mmm.end());
       }catch(exception e){
           isend=true;
       }
       isend=false;
       pattern ppp1=pattern.compile(".*?foo");
       matcher mmm1=ppp1.matcher("xfooxxxxxxfoo");
       /**
        * reluctant quantifiers 
           x??       x, once or not at all 
           x*?       x, zero or more times 
           x+?       x, one or more times 
           x{n}?     x, exactly n times 
           x(n,}?    x, at least n times 
           x{n,m}?   x, at least n but not more than m times 
           reluctant quantifiers的匹配方式正好相反,它总是先从最小匹配开始,如果这时导致
           整个串匹配失败则再吃进一个字符再试,如:
           .*?foo与xfooxxxxxxfoo的匹配过程,首先,.*与空串匹配,这时整个串匹配失败,于是
        *  再吃一个x,这时发现整个串匹配成功,当再调用find时从上次匹配结束时开始找,先吃一个
        *  空串,不行,再吃一个x,不行,……直到把中间所有x都吃掉才发现匹配成功。这种方式总
        *  是从最小匹配开始所以它能找到最多次数的匹配,但第一匹配都是最小的。它的行为有点象雇佣
        *  工人,总是尽可能少的于活,故名勉强的。
        */
       k=0;
       system.out.println("?????????????????????");
       system.out.println("xfooxxxxxxfoo");
       while(isend==false)
       try{
           system.out.println("the:"+k++);
           system.out.println(mmm1.find());
           system.out.println(mmm1.end());
       }catch(exception e){
           isend=true;
       }
       isend=false;
       pattern pp2=pattern.compile(".*+foo");
       matcher mm2=pp2.matcher("xfooxxxxxxfoo");
       /**
        * 
           possessive quantifiers 
           x?+        x, once or not at all 
           x*+        x, zero or more times 
           x++        x, one or more times 
           x{n}+      x, exactly n times 
           x(n,}+     x, at least n times 
           x{n,m}+    x, at least n but not more than m times 
           possessive quantifiers 这种匹配方式与greedy方式相似,所不同的是它不够聪明,当
           它一口吃掉所有可以吃的字符时发现不匹配则认为整个串都不匹配,它不会试着吐出几个。它的行
           为和大地主相似,贪婪但是愚蠢,所以名曰强占的。
        */

       int ii=0;
       system.out.println("+++++++++++++++++++++++++++");
       system.out.println("xfooxxxxxxfoo");
       while(isend==false)
       try{
           system.out.println("the:"+ii++);
           system.out.println(mm2.find());
           system.out.println(mm2.end());
       }catch(exception e){
           isend=true;
       }  
   } 
}