python正则表达式import re

正则表达式用来处理字符串的东西!下面代码来自莫凡python

https://morvanzhou.github.io/tutorials/python-basic/basic/13-10-regular-expression/

摘抄几个感觉很有用的例子,

import re
# r 讲解:
ptn = r"r[au]n"  # 前面这个r代表匹配到一个正则化表达式   表达式:[] 这里就是一个表达式了,ran或者run  

'''匹配多种可能 使用 []'''
# multiple patterns ("run" or "ran")
ptn = r"r[au]n"  # 前面这个r代表匹配到一个正则化表达式   表达式:[] 这里就是一个表达式了,ran或者run  
print(re.search(ptn, "dog runs to cat"))  
#<_sre.SRE_Match object; span=(4, 7), match='run'>
# continue
print(re.search(r"r[A-Z]n", "dog runs to cat"))     
print(re.search(r"r[a-z]n", "dog runs to cat"))     
print(re.search(r"r[0-9]n", "dog r2ns to cat"))     
print(re.search(r"r[0-9a-z]n", "dog runs to cat")) 
None
<_sre.SRE_Match object; span=(4, 7), match='run'>
<_sre.SRE_Match object; span=(4, 7), match='r2n'>
<_sre.SRE_Match object; span=(4, 7), match='run'>

'''任意字符'''
# . : match anything (except \n)
print(re.search(r"r.n", "r[ns to me"))     
<_sre.SRE_Match object; span=(0, 3), match='r[n'>

'''句尾句首'''
# ^ : match line beginning
print(re.search(r"^dog", "dog runs to cat"))        
# $ : match line ending
print(re.search(r"cat$", "dog runs to cat"))   
<_sre.SRE_Match object; span=(0, 3), match='dog'>
<_sre.SRE_Match object; span=(12, 15), match='cat'>

'''0或多次'''
# * : occur 0 or more times
print(re.search(r"ab*", "a"))                       
print(re.search(r"ab*", "abbbbb"))      
<_sre.SRE_Match object; span=(0, 1), match='a'>
<_sre.SRE_Match object; span=(0, 6), match='abbbbb'>

'''寻找所有匹配'''
# findall
print(re.findall(r"r[ua]n", "run ran ren"))    
['run', 'ran']
# | : or
print(re.findall(r"(run|ran)", "run ran ren"))  
['run', 'ran']

'''替换'''
# re.sub() replace
print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))   
dog catches to cat

'''分裂'''
# re.split()
print(re.split(r"[,;\.]", "a;b,c.d;e"))   
['a', 'b', 'c', 'd', 'e']

 

你可能感兴趣的:(python正则表达式import re)