用于匹配字符

简单的匹配

在python中使用正则表达式,需要调用内置的模块re

  1. import re
  2. # regular expression
  3. pattern1 = "cat"
  4. pattern2 = "bird"
  5. string = "dog runs to cat"
  6. print(re.search(pattern1, string)) # <re.Match object; span=(12, 15), match='cat'>
  7. print(re.search(pattern2, string)) # None

灵活匹配

如果需要找到潜在的多个可能性文字, 我们可以使用 [ ] 将可能的字符囊括进来。
注意:在字符串前面加r,表示不是简单的字符串类型

  1. import re
  2. # multiple patterns ("run" or "ran")
  3. ptn = r"r[au]n" # start with "r" means raw string
  4. print(re.search(ptn, "dog runs to cat")) # <re.Match object; span=(4, 7), match='run'>

此外 [A-Z] 表示的就是所有大写的英文字母. [0-9a-z] 表示可以是数字也可以是任何小写字母.

按类型

  • \d : 任何数字
  • \D : 不是数字
  • \s : 任何 white space, 如 [\t\n\r\f\v]
  • \S : 不是 white space
  • \w : 任何大小写字母, 数字和 [a-zA-Z0-9]
  • \W : 不是 \w
  • \b : 空白字符 (在某个字的开头或结尾)
  • \B : 空白字符 (在某个字的开头或结尾)
  • \ : 匹配 \
  • . : 匹配任何字符 (除了 \n)
  • ^ : 匹配开头
  • $ : 匹配结尾
  • ? : 前面的字符可有可无 ```python

    \d : decimal digit

    print(re.search(r”r\dn”, “run r4n”)) #

    \D : any non-decimal digit

    print(re.search(r”r\Dn”, “run r4n”)) #

\s : any white space [\t\n\r\f\v]

print(re.search(r”r\sn”, “r\nn r4n”)) #

\S : opposite to \s, any non-white space

print(re.search(r”r\Sn”, “r\nn r4n”)) #

\w : [a-zA-Z0-9_]

print(re.search(r”r\wn”, “r\nn r4n”)) #

\W : opposite to \w

print(re.search(r”r\Wn”, “r\nn r4n”)) #

\b : empty string (only at the start or end of the word)

print(re.search(r”\bruns\b”, “dog runs to cat”)) #

\B : empty string (but not at the start or end of a word)

print(re.search(r”\B runs \B”, “dog runs to cat”)) #

\ : match \

print(re.search(r”runs\“, “runs\ to me”)) #

. : match anything (except \n)

print(re.search(r”r.n”, “r[ns to me”)) #

^ : match line beginning

print(re.search(r”^dog”, “dog runs to cat”)) #

$ : match line ending

print(re.search(r”cat$”, “dog runs to cat”)) #

? : may or may not occur

print(re.search(r”Mon(day)?”, “Monday”)) # print(re.search(r”Mon(day)?”, “Mon”)) #

  1. 如果一个字符串有很多行, 我们想使用 ^ 形式来匹配行开头的字符, 如果用通常的形式是不成功的。此时要用一个参数, flags=re.M, 或者 flags=re.MULTILINE.
  2. ```python
  3. string = """
  4. dog runs to cat.
  5. I run to dog.
  6. """
  7. print(re.search(r"^I", string)) # None
  8. print(re.search(r"^I", string, flags=re.M)) # <_sre.SRE_Match object; span=(18, 19), match='I'>

重复匹配

  • * : 重复零次或多次
  • + : 重复一次或多次
  • {n, m} : 重复 n 至 m 次
  • {n} : 重复 n 次 ```python import re

* : occur 0 or more times

print(re.search(r”b“, “a”)) # print(re.search(r”b“, “abbbbb”)) # print(re.search(r”ab*”, “abbbbb”)) #

+ : occur 1 or more times

print(re.search(r”b+”, “a”)) # None print(re.search(r”b+”, “abbbbb”)) # print(re.search(r”ab+”, “abbbbb”)) #

{n, m} : occur n to m times

print(re.search(r”b{2,10}”, “a”)) # None print(re.search(r”b{2,10}”, “abbbbb”)) #

<a name="AqCso"></a>
### 分组
使用 `()` 为找到的内容分组. <br />比如在这个 `(\d+)` 组里, 需要找到的是一些数字, 在`(.+)`这个组里, 我们会找到后面的所有内容。<br />当使用 `.group()`时, 他会返回所有组里的内容, 而如果给 `.group(2) `里加一个数, 它就能定位你需要返回哪个组里的信息.
```python
import re

match = re.search(r"(\d+), Date: (.+)", "ID: 021523, Date: Feb/12/2017")
print(match.group())                   # 021523, Date: Feb/12/2017
print(match.group(1))                  # 021523
print(match.group(2))                  # Date: Feb/12/2017

有时候, 组很多, 光用数字可能比较难找到自己想要的组。
在括号的开头写上这样的形式 ?P<名字> 就给这个组定义了一个名字,然后就能用这个名字找到这个组的内容.

import re

match = re.search(r"(?P<id>\d+), Date: (?P<date>.+)", "ID: 021523, Date: Feb/12/2017")
print(match.group('id'))                # 021523
print(match.group('date'))              # Date: Feb/12/2017

findall

如果需要找到全部的匹配项, 我们可以使用findall功能。
会返回一个列表. 注意: | 是 or 的意思, 要不是前者要不是后者.、

import re

# findall
print(re.findall(r"r[ua]n", "run ran ren"))    # ['run', 'ran']

# | : or
print(re.findall(r"(run|ran)", "run ran ren")) # ['run', 'ran']

replace

使用这种匹配 re.sub(), 将会比 python 自带的 string.replace() 要灵活多变.

import re

print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))     # dog catches to cat

split

字符串的分割功能。
比如 “a is b”.split(“ “), 这样它就会产生一个列表来保存所有单词. 在正则中, 分割也可以做的淋漓精致。

import re

print(re.split(r"[,;\.]", "a;b,c.d;e"))             # ['a', 'b', 'c', 'd', 'e']

compile

可以使用 compile() 过后的正则, 来对这个正则重复使用.
先将正则 compile 进一个变量, 比如 compiled_re, 然后直接使用这个 compiled_re 来搜索.

import re

compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat"))  # <re.Match object; span=(4, 7), match='ran'>

13-10-01.png