码迷,mamicode.com
首页 > 其他好文 > 详细

正则表达式之基础(三)

时间:2016-11-02 00:46:34      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:表示   apt   没有   包含   情况   查找   his   匹配   att   

获取匹配

上面提到的子模式可以分为两种情况 - Capturing(获取匹配)和Non-Capturing(非获取匹配)

获取匹配:匹配时会将所有子模式匹配结果存储起来,可供后面查找或者替换,比如后向引用。

非获取匹配:子模式的匹配结果不会被存储,更多是作为一种限制条件,比如正反向肯定预查,正反向否定预查。

后向引用

使用“\数字”表示前面第几个子模式的匹配结果

例:

Text:

<h1>This is a capturing example</h1>

<h2>This is a capturing example2</h3>

Test Regular Expression:

<(h\d)>.*?</\1>

Results:

<h1>This is a capturing example</h1>

<h2>This is a capturing example2</h3>

这里的“\1”就是对前面第一个子模式(h\d)匹配结果的引用,也就是引用“h1”

后向引用的应用场景通常是:

1.     匹配合法的html标记,就像上面的例子

2.     匹配重复的内容

非获取匹配

(?:pattern)

在子模式内部前面添加“?:”则表示该子模式是一个非获取匹配,也就意味着不可用于后向引用。只匹配,不保存。

Text:

Windows 95 and Windows 98 are the successor.
Then Windows 2000 and Windows Xp appeared.
Windows Vista is the Latest version of the family.

Test Regular Expression:

Windows (?:\w+\b)

Results:

Windows 95 and Windows 98 are the successor.
Then Windows 2000 and Windows Xp appeared.
Windows Vista is the Latest version of the family.

(?=pattern)

正向肯定预查。 在子模式内部前面添加“?=”,表示该子模式仅仅作为匹配的限制条件,并不会被当做匹配结果输出,更谈不上保存匹配结果。预查是不消耗字符的,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从 包含预查的字符之后开始。可以理解为以什么结尾。

Text:

Windows 95 and Windows 98 are the successor.
Then Windows 2000 and Windows Xp appeared.
Windows Vista is the Latest version of the family.

Test Regular Expression:

Windows (?=\d+\b)

Results:

Windows 95 and Windows 98 are the successor.
Then Windows 2000 and Windows Xp appeared.
Windows Vista is the Latest version of the family.

Windows Vista和Windows Xp中的windows因不满足限制条件而没有匹配到

(?!pattern)

正向否定预查。在子模式内部前面添加“?!”,同正向肯定预查,表示该子模式仅作为匹配的条件。在上面的例子中,只有Windows Vista和Windows Xp中的windows会被匹配到并输出结果。可以理解为不以什么结尾。

(?<=pattern)

反向肯定预查,和正向预查差不多,只是预查的方向不一样。可以理解为以什么开头。

Text:

95 Windows and 98 Windows are the successor.
Then 2000 Windows and Xp Windows appeared.

Vista Windows is the Latest version of the family.

Test Regular Expression:

(?=\d+\b) Windows

Results:

95 Windows and 98 Windows are the successor.
Then 2000 Windows and Xp Windows appeared.

Vista Windows is the Latest version of the family.

(?<!pattern) - 反向否定预查,和正向预查差不多,只是预查的方向不一样。在上面的例子中Xp Windows和Vista Windows中的Windows会被匹配并输出。可以理解为不以什么开头。

正则表达式之基础(三)

标签:表示   apt   没有   包含   情况   查找   his   匹配   att   

原文地址:http://www.cnblogs.com/seanshao/p/6021298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!