Find a method .re modules:
1.findall matching elements each of which is a list of all
Re Import
RET = the re.findall ( '\ + D', '21313 ASD Luban the 7th') # regular expression character string to be matched, In Flag
# RET = the re.findall ( '\ D', 'the 7th ASD Luban 21313 ') # regular expression to be matched string, in Flag
# Print (RET)
2.search only match the first left to right, until the results are not directly, but rather a variable, the method to obtain the results of this variable group
Import Re
RET = the re.search ( ' \ + D ' , ' ASD Luban VII 21313 ' )
Print (RET) # memory address, which is the match for a positive result
Print (ret.group ()) # by ret.group ( ) to obtain real results
2.1 If there is no match to, will return None, using the group will complain
= the re.search RET ( ' \ + D ' , ' ASD Luban VII ' )
Print (ret.group ())
2.2 So this time I want to call what format
= the re.search RET ( ' \ + D ' , ' ASD Luban VII ' )
IF RET:
Print (ret.group ())
3.match scratch match, the equivalent of a regular expression search plus ^
= re.match RET ( ' \ + D ' , ' 1233asd Luban VII 21313 ' )
Print (RET)
II. Extended String Processing
1.split-- cutting
s = 'luban|cheng|an|'
print(s.split('|'))
s = 'luban34cheng21an89'
print(re.split('\d+',s))
2.sub-- replacement
K = re.sub ( ' \ d + ' , ' H ' , ' luban34cheng21an89 ' , 1 )
the printer (right)
3.subn returns a neuron progenitor, returns the number of the second element is replaceable
K = re.subn ( ' \ d + ' , ' H ' , ' luban34cheng21an89 ' )
the printer (right)
Advanced three .re module
1.compile save time you use regular expressions to solve problems, compiling regular expressions, compiled into byte code, in the course of a multiple use, not multiple compilations
= the re.compile RET ( ' \ + D ' ) # complete compiled
Print (RET)
RES = ret.findall ( ' luban34cheng21an89 ' )
Print (RES)
RES = ret.search ( ' 1233asd Luban VII 21313 ' )
Print (RES .group ())
2.finditer save space you use regular expressions to solve problems
ret = re.finditer('\d+','1233asd鲁班七号21313')
for i in ret:
print(i.group())
四.总结
findall 返回列表,找所有的匹配项
search 匹配就返回一个变量,通过group取匹配到的第一值,不匹配就返回None,group会报错
match 相当于search的正则表达式中加了一个'^'
split 返回列表,按照正则规则切割,默认匹配到的内容会被切掉
sub/subn 替换,按照正则规则去寻找要被替换的内容,subn返回元祖,第二个值是替换的次数
compile 编译一个正则表达式,用这个结果去search,match,fildall,finditer 能够节省时间
finditer 返回一个迭代器,所有的结果都在这个迭代器中,需要通过循环+group的形式取值 能够节省内存