Python基础语法 - 4 正则表达式和综合实战

2019-10-16  本文已影响0人  左心Chris

1 正则表达式的符号和特殊字符
2 正则表达式的匹配和分组
3 re库:compile match search findall sub split group groups groupdict

1. 正则表达式




有三个匹配模式:

2. 正则表达式的使用

a*bc 匹配0次或者多次a
a+bc 匹配1次或者多次a
a?bc 匹配0次或者1次a
a{3}bc 匹配3次a
a{2,5}bc 匹配2-5次a,优先匹配最多次的

3. 正则表达式匹配同类型及边界匹配

匹配同类型:

4. 正则表达式匹配选项

使用\来进行转义特殊字符
匹配选项:

5. 正则表达式分组

重复一个字符串进行匹配时

6. 贪婪和非贪婪模式

7. 实战匹配

8. python re模块

import re
pattern = re.compile(r'Hello', re.I)
rest = pattern.match('hello word')
print(dir(rest))
print(rest.string)
# 有两种方式,一个是编译,一个是不编译
# 编译
p = re.compile(r'[a-z]+', re.I)
rest = p.findall(content)
# 不编译
all_rest = re.findall(r'[a-z]+', content, re.I)
p = re.compile(r'(\d{6})(?P<year>\d{4})((?P<month>\d{2})(\d{2}))\d{1}([0-9]|X)')
id1 = '232321199410270017'
rest1 = p.search(id1)
print(rest1.group(4))
print(rest1.groups())
print(rest1.groupdict()) 
s = 'one1two2three'
p = re.compile(r'\d+')
rest = p.split(s, 2)
print(rest)
# 替换
s = 'one1two2three'
p = re.compile(r'\d+')
rest = p.sub('@', s)
# 替换位置
s1 = 'hello world'
p1 = re.compile(r'(\w+) (\w+)')
rest1 = p1.sub('r\2 \1', s1)
# 使用函数或者lambda来匹配
def f(m):
  return m.group(2).upper() + ' ' + m.group(1)
rest2 = p1.sub(f, s1)
rest3 = p1.sub(lambda m: m.group(2).upper() + ' ' + m.group(1), s1)

9. 实战取图片地址

import re
def test_image_url_extraction():
  with open('sample.html', encoding='utf-8') as f:
    html = f.read()
    p = re.compile(r'<img.+?src=\"(?P<src>.+?)\".+?>', re.M|re.I)
    list_img = p.findall(html)
    for i in list_img:
      print(i.replace('&amp;', '&'))
    # requests库去爬虫

10. 飞机大战

上一篇 下一篇

猜你喜欢

热点阅读