大数据 爬虫Python AI Sql

正则表达式

2018-05-05  本文已影响41人  SnailTyan

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 正则表达式

正则表达式(Regular Expression)描述了一种字符串匹配模式,主要用来检索、替换匹配某种模式的字符串。

2. 正则表达式语法

下面以Python代码来展示正则表达式的匹配。

import re
print(re.findall(r'.', 'abc'))

# 代码执行结果
['a', 'b', 'c']
import re
print(re.findall(r'^Th', 'This is a demo. This is a demo.'))

# 代码执行结果
['Th']
import re
print(re.findall(r'demo$', 'This is a demo. This is a demo'))

# 代码执行结果
['demo']
import re
print(re.findall(r'test*', 't te tes test testt'))

# 代码执行结果
['tes', 'test', 'testt']
import re
print(re.findall(r'test+', 't te tes test testt'))

# 代码执行结果
['test', 'testt']
import re
print(re.findall(r'test?', 't te tes test testt'))

# 代码执行结果
['tes', 'test', 'test']
import re
print(re.findall(r'test\?', 't te tes test? testt'))

# 代码执行结果
['test?']
import re
print(re.findall(r'te|st', 't te tes test'))

# 代码执行结果
['te', 'te', 'te', 'st']
import re
print(re.findall(r'[test]', 'This is a test'))

# 代码执行结果
['s', 's', 't', 'e', 's', 't']
import re
print(re.findall(r'[^test]', 'This is a test'))

# 代码执行结果
['T', 'h', 'i', ' ', 'i', ' ', 'a', ' ']
import re
print(re.findall(r'test{1,2}', 'This is a test testt'))

# 代码执行结果
['test', 'testt']
import re
print(re.findall(r'(test){1,2}', 'This is a test testt'))

# 代码执行结果
['test', 'test']
import re
print(re.findall(r'\w', 'Is this a test?_'))

# 代码执行结果
['I', 's', 't', 'h', 'i', 's', 'a', 't', 'e', 's', 't']
import re
print(re.findall(r'\W', 'Is this a test?'))

# 代码执行结果
[' ', ' ', ' ', '?']
import re
print(re.findall(r'\d', 'test 123'))

# 代码执行结果
['1', '2', '3']
import re
print(re.findall(r'\D', 'test 123'))

# 代码执行结果
['t', 'e', 's', 't', ' ']
import re
print(re.findall(r'\s', 'test 123\n'))

# 代码执行结果
[' ', '\n']
import re
print(re.findall(r'\S', 'test 123\n'))

# 代码执行结果
['t', 'e', 's', 't', '1', '2', '3']
import re
print(re.findall(r'\n', 'test 123\n'))

# 代码执行结果
['\n']
import re
print(re.findall(r'\f', 'test 123\f'))

# 代码执行结果
['\x0c']
import re
print(re.findall(r'\r', 'test 123\r'))

# 代码执行结果
['\r']
import re
print(re.findall(r'\t', 'test 123\t'))

# 代码执行结果
['\t']
import re
print(re.findall(r'\v', 'test 123\v'))

# 代码执行结果
['\x0b']
import re
print(re.findall(r'Th(?=is)', 'There or This or The?'))

# 代码执行结果,匹配的是This中的Th
['Th']
import re
print(re.findall(r'Th(?!is)', 'There or This or The?'))

# 代码执行结果,匹配的是There, The中的Th
['Th', 'Th']
import re
print(re.findall(r'(?<=H)e', 'The or He or She?'))

# 代码执行结果,匹配的是He中的e
['e']
import re
print(re.findall(r'(?<!H)e', 'The or He or She?'))

# 代码执行结果,匹配的是The, She中的e
['e', 'e']

参考资料

  1. https://juejin.im/entry/59a651116fb9a024844938b5
上一篇 下一篇

猜你喜欢

热点阅读