正则表达式边界符中的 ^, $, \A, \Z, \z

来源:互联网 发布:大学软件开发专业课程 编辑:程序博客网 时间:2024/06/07 00:09

转载自 http://blog.csdn.net/ggicci/article/details/8015087


Regex :
本文介绍正则表达式中边界符 ^ 和 $ 以及 \A 和 \Z, \z 的比较和用法
本文的正则表达式在 Java 中测试
本文的一些概念关键词以          高亮标出,正则表达式以           高亮标出
State :
这个是在 Java 7 的文档里截图下来的:



^ 和 $ 分别代表一行(line)的开始和结束的位置;\A 和 \z 分别代表输入(input)的开始和结束位置;\Z 代表输入的结尾位置,但是字符串的结尾可以有也可以没有终止子(final terminator:\n, \r, \r\n, \u0085, \u2028, \u2029)。
Line & Input (行和输入的区别):
行是以终止子作为标志结束的字符串片段,输入是整一段字符串。例如 "Ggicci is a good guy.\nGgicci's real name is OOXX.",这段字符串就是一个输入,其中 "Ggicci is a good guy." 就是一个行。
Single-line Mode & Multi-line Mode(匹配的单行模式和多行模式):
在用 Java 写一些匹配的时候,Pattern类的静态方法 static Pattern compile(String regex, int flags) 参数表中 flags 有DOTALL 和 MULTILINE 两个标志,DOTALL 表示表达式 . 能匹配任何字符,包括终止子,即通常所说的单行模式(single-line mode),此时,^ 和 $ 只能匹配整一个输入序列的开始和结束位置; MULTILINE 表示 ^, $ 能分辨出终止子的位置,即多行模式(multi-line mode)。
Sample_1 : ^,$ 在单行和多行模式下的匹配的差别
单行模式:
Input: "Google\nApple"  Regex: ^Google\nApple$     匹配到: "Google\nApple"
Input: "Google\nApple"  Regex: ^Google$                   匹配到: 无
多行模式:
Input: "Google\nApple"  Regex: ^Google\nApple$     匹配到: "Google\nApple"
Input: "Google\nApple"  Regex: ^Google$                   匹配到: "Google"
   1: String source = "Google\nApple";
   2: Pattern pattern = Pattern.compile("^Google\nApple$"); //--> "Google\nApple"
   3: //Pattern pattern = Pattern.compile("^Google$"); //--> null
   4: //Pattern pattern = Pattern.compile("^Google\nApple$", Pattern.MULTILINE); //--> "Google\nApple"
   5: //Pattern pattern = Pattern.compile("^Google$", Pattern.MULTILINE); //--> "Google"
   6: Matcher matcher = pattern.matcher(source);
   7: while (matcher.find()) {
   8:     System.out.println(matcher.group());
   9: }
Sample_2 : \z 和 \Z 的区别
        首先,\z 和 \Z 在单行和多行模式下都是对整个输入而言。\z 比较好理解,不管怎样,\A和\z匹配的是整段输入;而 \Z 匹配的时候在输入的结尾处有和没有终止子都能匹配。
Input: "Google\nApple"           Regex: \AGoogle\nApple\z  匹配到: "Google\nApple"
Input: "Google\nApple"           Regex: \AGoogle\nApple\Z  匹配的: "Google\nApple"
Input: "Google\nApple\n"       Regex: \AGoogle\nApple\z   匹配到: 无
Input: "Google\nApple\n"       Regex: \AGoogle\nApple\Z   匹配到: "Google\nApple" --> \Z 可以要求输入的结尾处有一个终止子,这里是\n当然换成\r或者\r\n也行
   1: String source = "Google\nApple";
   2: //String source = "Google\nApple\n";
   3: Pattern pattern = Pattern.compile("\\AGoogle\nApple\\Z");
   4: //Pattern pattern = Pattern.compile("\\AGoogle\nApple\\Z");
   5: Matcher matcher = pattern.matcher(source);
   6: while (matcher.find()) {
   7:     System.out.println(matcher.group());
   8: }
Conclusion :
\A 和 \z 匹配的是整段输入,完完整整,不偏不倚,不管在单行模式还是多行模式下
\A 和 \Z 匹配的是整段输入,结尾终止子可有可无,不管在单行模式还是多行模式下
^ 和 $ 在单行模式下匹配整段输入,同 \A 和 \z,在多行模式下匹配行,可以分辨终止子



0 0
原创粉丝点击