正则表达式 易混淆部分

来源:互联网 发布:手机js脚本例子 编辑:程序博客网 时间:2024/05/21 10:46

1、行结束符(line terminators),共 6

\n    , 字符串长度为 1 , ASCII码为 0x0A, 10 ,又被称为 new line, line feed, LF

\r    , 字符串长度为 1 , ASCII码为 0x0D, 13 ,又被称为 carriage-return, CR

\r\n字符串长度为  2  ,0D0A,这是 Windows 操作系统的 换行符

另外,Unicode 的三个字符定义,也是 Java 正则表达式 中的 line terminators

    a. '\u0085' ,next-line
    b. '\u2028' ,line-separator
    c. '\u2029' ,paragraph-separator

2、Pattern.DOTALL 只影响<<.>> ,无任何副作用

Pattern.DOTALL  即所谓的 “单行模式”,在Java中,被称为 DOTALL

只影响<<.>>,无任何副作用

默认:<<.>> 匹配 line terminators

DOTALL  后:<<.>> 匹配 line terminators

请看下面图片


3、Pattern.MULTILINE 只影响 <<^>> 和 <<$>> ,无任何副作用

Pattern.MULTILINE,多行模式

多行模式只影响行首行尾的锚定(anchor)(即 只影响 <<^>> 和 <<$>>),无任何副作用

默认:这两个表达式 仅仅 匹配字符串的开始和结束

MULTILINE后:

    a. 匹配字符串的开始和结束

    b. 匹配 line terminators 的开始和结束

这里的 “字符串” 即,即将应用到 正则的 “整个字符串”,无论 “整个字符串” 中包含了 多少个 line terminators

if NOT in MULTILINE model(这也是默认情况), ^,$ ignore line_terminator andonly match at the beginning and the end, respectively, of theentireinput sequence.

请看下面图片



<<$>>的特殊之处

即使<<$>>只匹配字符串的结束位置,仍然有一个例外的情况。如果字符串以 line terminator 结束,则<<$>>将会匹配 line terminator 前面的位置,而不是整个字符串的最后面

这个“改进”是由Perl引进的,然后被许多的正则表达式实现所遵循,包括Java,.NET等。如果应用<<^[a-z]+$>>到“joe\n”,则匹配结果是“joe”而不是“joe\n”

注意:<<$>>的这个特殊之处 和 是否 Pattern.MULTILINE 没有一毛钱关系

public static void main(String[] args) throws Exception {String inputString = "abc" + "\r\n";// 5System.out.println(inputString.length());// Pattern p = Pattern.compile("^abc{1}quot;);Pattern p = Pattern.compile("^abc{1}quot;, Pattern.MULTILINE);Matcher m = p.matcher(inputString);while (m.find()) {int start = m.start();int end = m.end();// Start:0, End:3System.out.println("Start:" + start + ", End:" + end);}}
<<^>>没有这个特殊之处

public static void main(String[] args) throws Exception {String inputString = "\r\n" + "abc";// 5System.out.println(inputString.length());Pattern p = Pattern.compile("^abc{1}quot;);Matcher m = p.matcher(inputString);// 根本进入不了 while// 因为 inputString 不是以 "a" 开头,而是以 "\r\na"开头while (m.find()) {int start = m.start();int end = m.end();System.out.println("Start:" + start + ", End:" + end);}}





原创粉丝点击