python正则表达式

import re
string = 'I love FishC.com'
# 查找FishC是否在I love FishC.com中
c = re.search(r'FishC', string)
print(c)
# <re.Match object; span=(7, 12), match='FishC'>

# .表示换行符之外的任何字符,故匹配到第一个字符I
d = re.search(r'.', string)
print(d)
# <re.Match object; span=(0, 1), match='I'>

# .表示换行符之外的任何字符,故匹配到FishC
e = re.search(r'Fish.', string)
print(e)
# re.Match object; span=(7, 12), match='FishC'>

# 如果想匹配.,则加反斜杠
f = re.search(r'.', string)
print(f)
# <re.Match object; span=(12, 13), match='.'>

# 反斜杠加d,匹配任何字符,故匹配到1
g = re.search(r'd',string + '123')
print(g)
# <re.Match object; span=(16, 17), match='1'>

h= re.search(r'ddd', string +'123456')
print(h)
# <re.Match object; span=(16, 19), match='123'>

# 匹配IP地址
i = re.search(r'ddd.ddd.ddd.ddd','192.168.111.156')
# 这样有三个问题:
# 1.这样写ddd最大可以匹配999,但是IP中最大的数字是255
# 2.有的IP点之间的数字是一位数或两位数,这样就匹配不到了
# 3.这样写太丑了
# 故下面开始优化
print(i)
# <re.Match object; span=(0, 15), match='192.168.111.156'>

# 中括号来创建字符类,表示范围,表示匹配到字符类中的任意一个字符就算匹配
# 字符类默认区分大小写的
# 如果不想区分大小写就可以加上大写的字母或关闭大小写敏感
j = re.search(r'[aeiou]', string)
# <re.Match object; span=(3, 4), match='o'>
print(j)
k= re.search(r'[aeiouAEIOU]', string)
print(k)
# <re.Match object; span=(0, 1), match='I'>

# 可以在字符类中加上-表示范围
l = re.search(r'[a-z]', string)
print(l)
# <re.Match object; span=(2, 3), match='l'>
m = re.search(r'[0-9]', string +'5678')
print(m)
# <re.Match object; span=(16, 17), match='5'>

# {}大括号解决匹配个数的问题,{3}表示前一个字符的3次,比如b{3}表示bbb
a = re.search(r'ab{3}c', 'abbbc')
print(a)
# <re.Match object; span=(0, 5), match='abbbc'>

# {3,10}表示前一个字符3次到10次,比如b{3,4}表示bbb或bbbb
a = re.search(r'ab{3,10}c', 'abbbbbbbbc')
# <re.Match object; span=(0, 10), match='abbbbbbbbc'>
print(a)

# 0-255的表示
a = re.search(r'[0-1]dd|2[0-4]d|25[0-5]', '188')
# <re.Match object; span=(0, 3), match='188'>
print(a)

# 匹配IP地址
# ()表示优先匹配,{0,1}表示可以有0个或1个
a = re.search(r'(([0-1]{0,1}d{0,1}d|2[0-4]d|25[0-5]).){3}([0-1]{0,1}d{0,1}d|2[0-4]d|25[0-5])'
,'192.168.1.1')
# <re.Match object; span=(0, 11), match='192.168.1.1'>
print(a)

原文地址:https://www.cnblogs.com/nnty/p/9927146.html