February 1, 2007

正则表达式中Lookbehind的用法

以前只知道用Lookahead,今天第一次遇到Lookbehind的实例。
下面这段摘自 regular-expressions.info (很好的一个正则站点):

Lookbehind has the same effect, but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. (? matches a “b” that is not preceded by an “a”, using negative lookbehind. It will not match cab, but will match the b (and only the b) in bed or debt. (?<=a)b (positive lookbehind) matches the b (and only the b) in cab, but does not match bed or debt.

The construct for positive lookbehind is (?<=text): a pair of round brackets, with the opening bracket followed by a question mark, “less than” symbol and an equals sign. Negative lookbehind is written as (?, using an exclamation point instead of an equals sign.

实例: 用正则表达式匹配特定字符串外的所有字符
方法: 匹配一个文本中的某个特定字符串很简单,但如何匹配某个特定字符串外的所有字符呢(类似反选功能)? 假定要搜索的特定字符串是SPRSTRING,利用正则表达式中的Lookbehind和Lookahead,在EmEditor中可以这样写:

(^|(?<=SPRSTRING)).*?(?=SPRSTRING|$)

这样匹配的就是除了SPRSTRING外的所有字符^o^

本文转自:http://lifesinger.org/?p=50

  您喜欢本文吗?即刻订阅"偶爱偶家",精彩文章不再错过!现在就给我们留个话吗?

 

« wordpress 2.1 ella 用windows live writer (wlw)发文快了许多 用notepad2中的收集功能替代SED »
One response to "正则表达式中Lookbehind的用法"
UGGboots said:
2009年11月24日

http://www.6inchboot.com/

UGG boots;cheap UGG;UGG classic

[Reply]

Leave a comment