1.用多个分隔符分隔字符串
import re
line = 'abc,123; yes no'
result = re.split(r"[;,\s]\s*",line)
assert ['abc', '123', 'yes', 'no'] == result
2.匹配和查找字符串
import re
text1 = "11/27/2012"
text2 = 'Nov 27,2012'
assert re.match(r'\d+/\d+/\d+',text1)
assert not re.match(r'\d+/\d+/\d+',text2)
#only check the beginning
assert re.match(r'\d+/\d+/\d+',text1+'abc')
assert not re.match(r'\d+/\d+/\d+$',text1+'abc')
datepat = re.compile(r'\d+/\d+/\d+')
assert datepat.match(text1)
assert ['2/4/2019', '1/01/9102'] == datepat.findall('Today is 2/4/2019,it is 1/01/9102 soon')
3.替换字符串
import re
text1 = "Today is 4/27/2019"
assert "Today is 2019-4-27" == re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text1)
datepat =re.compile(r'(\d+)/(\d+)/(\d+)')
assert datepat.sub(r'\3-\1-\2', text1) == "Today is 2019-4-27"
# use callback
def change_date(m):
return f"{m.group(3)}-{m.group(1)}-{m.group(2)}"
assert datepat.sub(change_date, text1) == "Today is 2019-4-27"
网友评论