- import re
-
- str = 'Hi \n _12'
- print(str)
一、除换行符之外的任意字符
- print(re.findall(".",str))
- # 连着两个
- print(re.findall("..",str))
- # 连着三个
- print(re.findall("...",str))
- print(re.findall("....",str))
二、 字母、数字、下划线
- print(re.findall("\w", str))
- # 连着两个
- print(re.findall("\w\w", str))
- # 连着三个
- print(re.findall("\w\w\w", str))
三、数字
print(re.findall("\d", str))
四、空格、换行符
print(re.findall("\s", str))
五、非字母、数字、下划线
print(re.findall("\W", str))
六、非数字
print(re.findall("\D", str))
七、非空格、换行符
print(re.findall("\S", str))
例:
- str2 = 'Hello World 123'
-
- print(re.findall('e', str2))
- print(re.findall('ll', str2))
- print(re.findall('l\n', str2))
- print(re.findall('[abcd]', str2))
- print(re.findall('[12][12]', str2))
- print(re.findall('[12]..', str2))
- print(re.findall('[a-f]', str2))
- print(re.findall('[0-2a-e]', str2))
- print(re.findall('[^a-e]', str2))
- str3 = '122333 abbccc'
-
- print(re.findall("\d{3}", str3))
- print(re.findall("\w{3}", str3))
- print(re.findall("1*", str3))
- print(re.findall("1*2", str3))
- print(re.findall("1*3", str3))
- print(re.findall("1+", str3))
- print(re.findall("1+2", str3))
- print(re.findall("1+3", str3))
- print(re.findall("\d*", str3))
- print(re.findall("\d+", str3))
- print(re.findall("\d+3", str3))
- import re
- str = 'X1Y22Y333Y4444'
-
- # 贪婪匹配
- print(re.findall("X.*Y",str))
- # ['X1Y22Y33Y']
-
- # 惰性匹配
- print(re.findall("X.*?Y",str))
- # ['X1Y']
-
- print(re.findall("\d*Y",str))
- # ['1Y22Y333Y']
- print(re.findall("\d.*?Y",str))
- # ['1Y','22Y','333Y']
- str2 = 'Hello World 123'
-
- exp = re.compile('\w+')
- print(exp.findall(str2))
- str3 = 'My name is Martini!'
- exp = re.compile('is (.*)!')
- print(exp.findall(str3))
-
-
- str4 = 'My name is Martini!My name is Sam!My name is Tom!'
- # exp = re.compile('is (.*)!')
- # exp = re.compile('is (.*?)!')
- print(exp.findall(str4))
-
-
- str5 = '''
- My name is Martini,and i am 25 years old!
- My name is Sam,and i am 27 years old!
- My name is Tom,and i am 23 years old!'
- exp = re.compile('is (.*?),.*?am (\d+)')
- # print(exp.findall(str5))
- for i,j in exp.findall(str5):
- print(i,j)