正则表达式
正则表达式是一种用来描述字符串模式的方法。它是一种强大的工具,用于在文本中搜索、匹配和编辑特定模式的字符串。正则表达式可以用来验证输入是否符合某种模式,提取文本中的特定信息,以及进行文本的替换和分割等操作。在计算机编程和文本处理中,正则表达式被广泛应用于各种领域,如文本搜索引擎、数据分析、文本编辑器等。
re模块
re模块是Python中用于处理正则表达式的标准库。它提供了一系列函数来进行正则表达式的匹配、搜索和替换操作。
re模块常用的函数
re.compile(pattern, flags=0):
编译正则表达式模式,返回一个正则表达式对象。
import re
pattern = re.compile(r'\d+') # 匹配一个或多个数字
re.search(pattern, string, flags=0):
在字符串中搜索第一个匹配项,返回一个匹配对象。
match = re.search(r'\d+', 'There are 123 apples')
re.match(pattern, string, flags=0):
尝试从字符串的起始位置匹配一个模式,返回一个匹配对象。如果字符串起始位置没有匹配成功,则返回None。
match = re.match(r'\d+', '123 apples')
re.findall(pattern, string, flags=0):
在字符串中查找所有匹配项,返回一个包含所有匹配结果的列表。
matches = re.findall(r'\d+', 'There are 123 apples and 456 bananas')
re.finditer(pattern, string, flags=0):
在字符串中查找所有匹配项,返回一个包含所有匹配结果的迭代器。
matches = re.finditer(r'\d+', 'There are 123 apples and 456 bananas')
re.sub(pattern, repl, string, count=0, flags=0):
使用新字符串替换所有匹配的字符串。
new_string = re.sub(r'\d+', 'X', 'There are 123 apples and 456 bananas')
一些练习题
1、匹配出下列各项字符串中是IP地址的字符串。
123
255.255.255.0
192.168.0.1
256.1.1.1
This is a string.
123.123.0
import restrs=["123","255.255.255.0","192.168.0.1","256.1.1.1","This is a string","123.123.0"]
pattern= re.compile(r'^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}')for i in strs:str1=re.compile(pattern).findall(i)if str1:print("是ip字符串")else:print("不是ip字符串")
2、请对以下文本中十六进制的RGB颜色值进行匹配。
提示:通过一个以“#”开头的6位十六进制数值表示一种颜色。6位数字分为3组,每组两位,依次表示红、绿、蓝三种颜色的强度。
#00
#ffffff
#ffaaff
#00hh00
#aabbcc
#000000
#fffffff
以上二题可用在线测试工具测试:http://regex101.com, 加深对字符的理解
import repattern="#[a-fA-F0-9]{6}"
str1=["#00",
"#ffffff",
"#ffaaff",
"#00hh00",
"#aabbcc",
"#000000",
"#fffffff"
]for i in str1:str2=re.compile(pattern).findall(i)if str2:print("是RGB")else:print("不是RGB")
3、判断字符串是否是全部小写
s1 = ‘adkkdk’
s2 = ‘abc123efg’
(1)使用re.search和re.group解答
(2)使用re.match和re.group解答
import res1="adkkdk"
s2="abc123efg"
an = re.match('^[a-z]+$', s1)
if an:print("s1",an.group(),"全为小写")
else:print(s1,"不全是小写")an=re.search(" ^[a-z]+$",s2)
if an:print('s2',an.group(),"全为小写")else:print(s2,"不全为小写")
4、按照邮箱通用格式,匹配其中的email地址。(使用re.findall解题)
18611323113@163.com xxx@qq.com 969651238@.com 741852963qq.com
import restr1="18611323113@163.com xxx@qq.com 969651238@.com 741852963qq.com"
#pattern=r'([\w]+(\.[\w]+)*@[\w]+(\.[\w])+)'data=re.compile("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}").findall(str1)
print(data)
5、(1)使用re.split将下列给出字符串中的数字与字母分割开,一种为不保留匹配项,另一种为保留匹配项。
(2)使用re.sub将字符串中所有的字母替换成A
1234abc567def
import restr1="1234abc567def"print(re.split("\d+",str1))
print(re.split("[A-Za-z]+",str1))print(re.split("(\d+)|([A-Za-z]\s)",str1))str2=re.sub("[A-Z-a-z]",'A',str1)
print(str2)
6、使用re.findall匹配下列语句中的所有单词的首字母,并统计这些首字母出现的频次。
You are beautiful, gay, giving, gentle, idiotically and deliciously feminine, sexy, wonderfully intelligent and wonderfully silly as well.
import re
'''
en_text="You are beautiful, gay, giving, gentle, idiotically and deliciously feminine, sexy, wonderfully intelligent and wonderfully silly as well."en_text = en_text.replace(',',' ').replace('.',' ')
text = en_text.split()
d = {}
for i in text:for j in i[:1]:if j in d:d[j]+=1else:d[j]=1
print(d)
'''import re
import pandas as pd
s="You are beautiful, gay, giving, gentle, idiotically and deliciously feminine, sexy, wonderfully intelligent and wonderfully silly as well."
content=re.findall(r"\b\w",s)
print (content)
pd.DataFrame(content).value_counts()
7、对下列字符串进行贪婪匹配与懒惰匹配。
The sixth sick sheikh have six sheep sick.
①懒惰匹配:regex = s.*?s
②贪婪匹配:regex = s.*s
import re
str1="The sixth sick sheikh have six sheep sick."
m=re.findall('s.*? s',str1)
print (m)
m=re.findall('s.* s',str1)
print (m)
8、将下列字符串中非符号的部分提取出来。(使用re.findall和选择符解答)
import re
text = "(/*gsgsdgs45df5sd4f5d4f65*/)"
m = re.findall("(?<=/\*)[a-zA-Z0-9]+(?=\*/)",text)
print (m)#此处还可以将[a-zA-Z0-9]+ 改成.+ 或者\w+
9、验证输入的手机号码是否合法。(使用re.match和re.group)
手机号码:13634222222;13144222221
import repattern = r'(13[4-9]\d{8})$|(15[01289]d{8})$'
mobile = ['13634222222','13144222221']
for i in mobile:match = re.match(pattern,i)if match:print(i,"是合法的手机号")else:print(i,"不是合法的手机号")