正则表达式学习笔记(四)——位置匹配

1.1单词边界

限定符指定单词边界,b是英文boundary(边界)的首字母,例如

文本:The catscattered his food all over the room.

正则表达式:cat

结果: The cat scatteredhis food all over the room.

正则表达式:cat

结果: The cat scattered his food all overthe room.

如果想不匹配一个单词的边界(),使用B ,例如下面的例子匹配多余的空格

文本: please enter the nine-digit id as it appears on your color – cpdedpass-key

正则表达式:B-B

结果:please enter the nine-digit id as it appears on your color - cpdedpass-key

分析:B-B

将匹配一个前后都不是单词边界的连字符(因为空格和连字符都不是字母数字或下划线)。只有color – cpded中的连字符可以与之匹配

1.2字符串边界

1.2.1匹配字符串开头

我们知道使用^可以用来取非,其实他还有匹配一个字符串的开头的作用。

当^出现在一个字符集合中(被放到[和]之间)并且紧跟在左方括号[的后面是,才能发挥“求非”作用。

如果是在一个字符集合的外面并且位于一个模式的开头,^将匹配字符串的开头。例如,下面的测试可以检查一个文档是否为xml文档(xml文档必须是<?xmlversion="1.0"?>类型,而且必须放在开头)

文本

this is not a xml document, real not a xmldocument

<?xml version="1.0"ecoding=”utf-8” ?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML1.1//EN" " >
<wml>
<head>
<access/>

正则表达式:<?xml.*?>

结果

this is not a xml document, real not a xmldocument

<?xml version="1.0"ecoding=”utf-8” ?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML1.1//EN" " >
<wml>
<head>
<access/>

我们就以为这是xml文件了,其实这不是xml文件,xml文件必须是在开头有上述标示才行

正确的正则表达式:^s*<?xml.*??>

 1.2.2 匹配字符串结尾

使用$即可

1.2.3  分行匹配

(?m)说明是分行模式,必须出现在整个模式的最前面,下例将会找出所有的注释文章

文本:

String author()default "aaa";
 //aaaaaaa

 int[]arrayAttr() default {1};
 //bbbbbbbb
 MetaAnnotation annotationAttr() default@MetaAnnotation("");
 //ccccccc
 Class<PersonChiness> classType()default PersonChiness.class;

正则表达式:(?m)^s*//.*$

结果:Stringauthor() default "aaa";
 //aaaaaaa

 int[]arrayAttr() default {1};
 //bbbbbbbb
 MetaAnnotation annotationAttr() default@MetaAnnotation("");
 //ccccccc
 Class<PersonChiness> classType()default PersonChiness.class;
警告:有许多正则表达式不支持(?m)

原文地址:https://www.cnblogs.com/thiaoqueen/p/7675234.html