快乐的鲸鱼

Python 正则表达式

2015/12/04

以下是一段分析邮箱的正则表达式

1
2
3
4
5
6
import re

m = re.match(r'^([0-9a-zA-Z]+)\@([0-9a-zA-Z]+\.com)$', 'toono@qq.com')
print(m.group(0))
print(m.group(1))
print(m.group(2))

输出:

1
2
3
toono@qq.com
toono
@qq.com

接下来分析上面的正则表达式

r’^([0-9a-zA-Z]+)@([0-9a-zA-Z]+.com)$’

  • r’ ‘ 是需要import re的,作用是在引号内的内容不进行转义
  • ^ 是表示以^符号以后的一个字符进行开头的匹配
  • $ 是表示以$符号前一个字符进行结尾的匹配
  • [0-9a-zA-Z] 表示匹配一个字符,可以是0到9、a到z、A到Z
  • [0-9a-zA-Z]+ 表示匹配一个以上字符,可以是0到9、a到z、A到Z
  • @ 防止符号转义
  • () 括号表示一个组,方便group()函数调用

切分字符串

用正则表达式切分字符串

1
re.split(r'\s+', 'a b   c')

输出

1
['a', 'b', 'c']

截取字符串

1
2
pattern = re.compile(r"(\d+).")
current_page = pattern.search("https://yuming-1-34.html").group()[:-1]

替换字符串

1
2
next_page = str(int(current_page)+1) + ".html"
next_page = re.sub(r"(\d+).html", next_page, "https://yuming-1-34.html")
CATALOG
  1. 1. 切分字符串
  2. 2. 截取字符串
  3. 3. 替换字符串