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'>spa

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

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

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

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

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

# 中括号来建立字符类,表示范围,表示匹配到字符类中的任意一个字符就算匹配
# 字符类默认区分大小写的
# 若是不想区分大小写就能够加上大写的字母或关闭大小写敏感
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'>co

# 能够在字符类中加上-表示范围
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]\d\d|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)

相关文章
相关标签/搜索