高级正则表达式技术(Python版)

前端之家收集整理的这篇文章主要介绍了高级正则表达式技术(Python版)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


正则表达式是从信息中搜索特定的模式的一把瑞士军刀。它们是一个巨大的工具库,其中的一些功能经常被忽视或未被充分利用。今天我将向你们展示一些正则表达式的高级用法

举个例子,这是一个我们可能用来检测电话美国电话号码的正则表达式:

1
r@H_301_25@ '^(1[-\s.])?(\()?\d{3}(?(2)\))[-\s.]?\d{3}[-\s.]?\d{4}$'@H_301_25@

我们可以加上一些注释和空格使得它更具有可读性。

1
2
3
4
5
6
7
8
9
'^'@H_301_25@
'(1[-\s.])?'@H_301_25@ # optional '1-','1.' or '1'@H_301_25@
'(\()?'@H_301_25@      # optional opening parenthesis@H_301_25@
'\d{3}'@H_301_25@      # the area code@H_301_25@
'(?(2)\))'@H_301_25@   # if there was opening parenthesis,close it@H_301_25@
'[-\s.]?'@H_301_25@    # followed by '-' or '.' or space@H_301_25@
# first 3 digits@H_301_25@
# followed by '-' or '.' or space@H_301_25@
'\d{4}$'@H_301_25@    # last 4 digits@H_301_25@

让我们把它放到一个代码片段里:

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import@H_301_25@ re@H_301_25@
 
numbers @H_301_25@ =@H_301_25@ [ @H_301_25@ "123 555 6789"@H_301_25@ ,@H_301_25@
            @H_301_25@ "1-(123)-555-6789"@H_301_25@ 301_25@
"(123-555-6789"@H_301_25@ 301_25@
"(123).555.6789"@H_301_25@ 301_25@
"123 55 6789"@H_301_25@ ]@H_301_25@
 
for@H_301_25@ number @H_301_25@ in@H_301_25@ numbers:@H_301_25@
    @H_301_25@ pattern @H_301_25@ re.match(r@H_301_25@ '^'@H_301_25@
                   @H_301_25@ '(1[-\s.])?'@H_301_25@           301_25@
'(\()?'@H_301_25@                # optional opening parenthesis@H_301_25@
'\d{3}'@H_301_25@                # the area code@H_301_25@
'(?(2)\))'@H_301_25@             301_25@
'[-\s.]?'@H_301_25@              # followed by '-' or '.' or space@H_301_25@
# first 3 digits@H_301_25@
# followed by '-' or '.' or space@H_301_25@
'\d{4}$\s*'@H_301_25@ 301_25@ # last 4 digits@H_301_25@
 
    @H_301_25@ if@H_301_25@ pattern:@H_301_25@
        @H_301_25@ print@H_301_25@ '{0} is valid'@H_301_25@ .@H_301_25@ format@H_301_25@ (number)@H_301_25@
else@H_301_25@ :@H_301_25@
        @H_301_25@ print@H_301_25@ '{0} is not valid'@H_301_25@ (number)@H_301_25@

输出,不带空格:

5
123@H_301_25@ 555@H_301_25@ 6789@H_301_25@ is@H_301_25@ valid@H_301_25@
1@H_301_25@ -@H_301_25@ (@H_301_25@ 123@H_301_25@ )@H_301_25@ -@H_301_25@ 555@H_301_25@ 6789@H_301_25@ valid@H_301_25@
123@H_301_25@ is@H_301_25@ not@H_301_25@ valid@H_301_25@
).@H_301_25@ 555.6789@H_301_25@ valid@H_301_25@
55@H_301_25@ valid@H_301_25@

正则表达式是 python 的一个很好的功能,但是调试它们很艰难,而且正则表达式很容易就出错。

幸运的是,python 可以通过对 re.compile@H_301_25@ 或 re.match@H_301_25@ 设置 re.DEBUG@H_301_25@ (实际上就是整数 128) 标志就可以输出正则表达式的解析树。

@H_301_356@ 23
                    @H_301_25@ '(1[-\s.])?'@H_301_25@        '(\()?'@H_301_25@             '\d{3}'@H_301_25@             '(?(2)\))'@H_301_25@          '[-\s.]?'@H_301_25@           '\d{4}$'@H_301_25@ 301_25@ (number)@H_301_25@

解析树

23
24
25
26
27
28
@H_646_403@ 29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
at_beginning@H_301_25@
max_repeat @H_301_25@ 0@H_301_25@ 1@H_301_25@
  @H_301_25@ subpattern @H_301_25@ 1@H_301_25@
literal @H_301_25@ 49@H_301_25@
in@H_301_25@
      @H_301_25@ 45@H_301_25@
category category_space@H_301_25@
46@H_301_25@
2147483648@H_301_25@
  @H_301_25@ in@H_301_25@
category category_space@H_301_25@
1@H_301_25@
2@H_301_25@
40@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
3@H_301_25@ 3@H_301_25@
in@H_301_25@
category category_digit@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
subpattern @H_301_25@ None@H_301_25@
groupref_exists @H_301_25@ 2@H_301_25@
41@H_301_25@
None@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
1@H_301_25@
in@H_301_25@
45@H_301_25@
category category_space@H_301_25@
46@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
3@H_301_25@
in@H_301_25@
category category_digit@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
1@H_301_25@
in@H_301_25@
45@H_301_25@
category category_space@H_301_25@
46@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
4@H_301_25@ 4@H_301_25@
in@H_301_25@
category category_digit@H_301_25@
at at_end@H_301_25@
2147483648@H_301_25@
in@H_301_25@
category category_space@H_301_25@
valid@H_301_25@
valid@H_301_25@
valid@H_301_25@
valid@H_301_25@
valid@H_301_25@

贪婪和非贪婪

在我解释这个概念之前,我想先展示一个例子。我们要从一段 html 文本寻找锚标签

7
html @H_301_25@ =@H_301_25@ 'Hello <a href="http://pypix.com" title="pypix">Pypix</a>'@H_301_25@
 
m @H_301_25@ re.findall(@H_301_25@ '<a.*>.*<\/a>'@H_301_25@ 301_25@
m:@H_301_25@
    @H_301_25@ print@H_301_25@ m@H_301_25@

结果将在意料之中:

[@H_301_25@ '<a href="http://pypix.com" title="pypix">Pypix</a>'@H_301_25@ ]@H_301_25@

我们改下输入,添加第二个锚标签

8
'Hello <a href="http://pypix.com" title="pypix">Pypix</a>'@H_301_25@ \@H_301_25@
       @H_301_25@ 'Hello <a href="http://example.com" title"example">Example</a>'@H_301_25@
 
301_25@
m:@H_301_25@
m@H_301_25@

结果看起来再次对了。但是不要上当了!如果我们在同一行遇到两个锚标签后,它将不再正确工作:

1
'<a href="http://pypix.com" title="pypix">Pypix</a>Hello <a href="http://example.com" title"example">Example</a>'@H_301_25@ ]@H_301_25@

这次模式匹配了第一个开标签和最后一个闭标签以及在它们之间的所有的内容,成了一个匹配而不是两个 单独的匹配。这是因为默认的匹配模式是“贪婪的”。

当处于贪婪模式时,量词(比如 *@H_301_25@ 和 +@H_301_25@)匹配尽可能多的字符。

当你加一个问号在后面时(.*?@H_301_25@)它将变为“非贪婪的”。

'<a.*?>.*?<\/a>'@H_301_25@ m@H_301_25@

现在结果是正确的。

1
301_25@ '<a href="http://example.com" title"example">Example</a>'@H_301_25@ ]@H_301_25@

前向界定符和后向界定符

一个前向界定符搜索当前的匹配之后搜索匹配。通过一个例子比较好解释一点。

下面的模式首先匹配 foo@H_301_25@,然后检测是否接着匹配 bar@H_301_25@:

11
strings @H_301_25@ [  @H_301_25@ "hello foo"@H_301_25@ 301_25@ # returns False@H_301_25@
             @H_301_25@ "hello foobar"@H_301_25@  ]    @H_301_25@ # returns True@H_301_25@
string @H_301_25@ strings:@H_301_25@
re.search(r@H_301_25@ 'foo(?=bar)'@H_301_25@ 301_25@
pattern:@H_301_25@
'True'@H_301_25@
:@H_301_25@
'False'@H_301_25@

这看起来似乎没什么用,因为我们可以直接检测 foobar@H_301_25@ 不是更简单么。然而,它也可以用来前向否定界定。 下面的例子匹配foo@H_301_25@,当且仅当它的后面没有跟着 bar@H_301_25@。

12
# returns True@H_301_25@
"hello foobar"@H_301_25@ 301_25@ # returns False@H_301_25@
"hello foobaz"@H_301_25@ ]      @H_301_25@ # returns True@H_301_25@
 
strings:@H_301_25@
'foo(?!bar)'@H_301_25@ 301_25@
pattern:@H_301_25@
'True'@H_301_25@
:@H_301_25@
'False'@H_301_25@

后向界定符类似,但是它查看当前匹配的前面的模式。你可以使用 (?>@H_301_25@ 来表示肯定界定,(?<!@H_301_25@ 表示否定界定。

下面的模式匹配一个不是跟在 foo@H_301_25@ 后面的 bar@H_301_25@。

"hello bar"@H_301_25@ "hello bazbar"@H_301_25@ '(?<!foo)bar'@H_301_25@ 'False'@H_301_25@

条件(IF-Then-Else)模式

正则表达式提供了条件检测的功能。格式如下:

(?(?=regex)then|else)

条件可以是一个数字。表示引用前面捕捉到的分组。

比如我们可以用这个正则表达式来检测打开和闭合的尖括号:

13
"<pypix>"@H_301_25@ 301_25@ # returns true@H_301_25@
"<foo"@H_301_25@ 301_25@ # returns false@H_301_25@
"bar>"@H_301_25@ # returns false@H_301_25@
"hello"@H_301_25@ ]     @H_301_25@ # returns true@H_301_25@
 
strings:@H_301_25@
'^(<)?[a-z]+(?(1)>)$'@H_301_25@ 301_25@
pattern:@H_301_25@
'True'@H_301_25@
:@H_301_25@
'False'@H_301_25@

在上面的例子中,1@H_301_25@ 表示分组 (<)@H_301_25@,当然也可以为空因为后面跟着一个问号。当且仅当条件成立时它才匹配关闭的尖括号。

条件也可以是界定符。

无捕获组

分组,由圆括号括起来,将会捕获到一个数组,然后在后面要用的时候可以被引用。但是我们也可以不捕获它们。

我们先看一个非常简单的例子:

re          @H_301_25@
string @H_301_25@ 'Hello foobar'@H_301_25@         
'(f.*)(b.*)'@H_301_25@ 301_25@
"f* => {0}"@H_301_25@ (pattern.group(@H_301_25@ 1@H_301_25@ )) @H_301_25@ # prints f* => foo          @H_301_25@
"b* => {0}"@H_301_25@ 2@H_301_25@ # prints b* => bar@H_301_25@

现在我们改动一点点,在前面加上另外一个分组 (H.*)@H_301_25@:

'(H.*)(f.*)(b.*)'@H_301_25@ # prints f* => Hello          @H_301_25@
# prints b* => bar@H_301_25@

模式数组改变了,取决于我们在代码中怎么使用这些变量,这可能会使我们的脚本不能正常工作。 现在我们不得不找到代码中每一处出现了模式数组的地方,然后相应地调整下标。 如果我们真的对一个新添加的分组的内容没兴趣的话,我们可以使它“不被捕获”,就像这样:

'(?:H.*)(f.*)(b.*)'@H_301_25@ # prints b* => bar@H_301_25@

通过在分组的前面添加 ?:@H_301_25@,我们就再也不用在模式数组中捕获它了。所以数组中其他的值也不需要移动。

命名组

像前面那个例子一样,这又是一个防止我们掉进陷阱的方法。我们实际上可以给分组命名, 然后我们就可以通过名字来引用它们,而不再需要使用数组下标。格式是:(?Ppattern)@H_301_25@ 我们可以重写前面那个例子,就像这样:

'(?P<fstar>f.*)(?P<bstar>b.*)'@H_301_25@ (pattern.group(@H_301_25@ 'fstar'@H_301_25@ 'bstar'@H_301_25@ # prints b* => bar@H_301_25@

现在我们可以添加另外一个分组了,而不会影响模式数组里其他的已存在的组:

6
'(?P<hi>H.*)(?P<fstar>f.*)(?P<bstar>b.*)'@H_301_25@ # prints b* => bar          @H_301_25@
"h* => {0}"@H_301_25@ 'hi'@H_301_25@ # prints b* => Hello@H_301_25@

使用回调函数

在 Python 中 re.sub()@H_301_25@ 可以用来给正则表达式替换添加回调函数

让我们来看看这个例子,这是一个 e-mail 模板:

22
template @H_301_25@ "Hello [first_name] [last_name],\          @H_301_25@
 @H_301_25@ Thank you @H_301_25@ purchasing [product_name] @H_301_25@ from@H_301_25@ [store_name]. \          @H_301_25@
The total cost of your purchase was [product_price] plus [ship_price] @H_301_25@ shipping. \          @H_301_25@
You can expect your product to arrive @H_301_25@ [ship_days_min] to [ship_days_max] business days. \          @H_301_25@
Sincerely,\          @H_301_25@
[store_manager_name]"          @H_301_25@
# assume dic has all the replacement data          @H_301_25@
# such as dic['first_name'] dic['product_price'] etc...          @H_301_25@
dic @H_301_25@ {          @H_301_25@
 @H_301_25@ "first_name"@H_301_25@ : @H_301_25@ "John"@H_301_25@ 301_25@
"last_name"@H_301_25@ "Doe"@H_301_25@ 301_25@
"product_name"@H_301_25@ "iphone"@H_301_25@ 301_25@
"store_name"@H_301_25@ "Walkers"@H_301_25@ 301_25@
"product_price"@H_301_25@ : @H_301_25@ "$500"@H_301_25@ 301_25@
"ship_price"@H_301_25@ "$10"@H_301_25@

猜你在找的正则表达式相关文章