python13_1day正则表达式

re正则表达式

通配符.

对特殊字符进行转义\

字符集[a-z]匹配其中的任意字符,[^a]匹配除a以外的其它字母

选择符和自模式

管道符号(|),匹配’python|perl’

‘p(ython|erl)’

可选项和重复子模式

在子模式后面加上问号,它就变成了可选项r’(http:\)?

()*重复0次或多次

()+重复1次或多次

(){m,n}重复m~n次

import re

re.compile # 根据包含正则表达式的字符串创建模式对象
re.search # 在字符串中寻找模式
re.match # 在字符串的开始出匹配模式
re.split # 根据模式的匹配项来分割字符串
re.findall # 列出字符串模式中所有的匹配项
re.escape # 将字符串中所有特殊正则表达式字符转义

group#获取给定模式的匹配项

start#返回给定组的匹配项开始的位置

end#返回给定组的匹配项结束的位置

span#返回一个组结束和开始的位置

m = re.match(r’www.(.*)…{3}’, ‘www.python.org’)
print(m)
print(m.group(1))
print(m.start(1))
print(m.end(1))
print(m.span(1))
import re
import fileinput

file_pat = re.compile(r’[(.+?)]’)
scope = {}

def replacement(match):
code = match.gruop(1)
try:
return str(eval(code, scope))
except SyntaxError:
exec(code in scope)
return ‘’

lines = []
for line in fileinput.input(‘alice.txt’, ‘r’):
lines.append(line)
text = ‘’.join(lines)
print(file_pat.sub(replacement, text))

seek自己定义当前读和写的位置

猜你喜欢

转载自blog.csdn.net/qq_38501057/article/details/88426929