未完成
参考链接
re.sub使用
- re是regular expression的所写,表示正则表达式;sub是substitute的所写,表示替换。
re.sub(pattern, repl, string, count=0, flags=0)
- pattern是正则表达式模板,eg:"$p(?P<delta_days>\d+)d"
- repl是替换的字符,也可以是替换规则的函数
- count是替换的次数,默认全部替换
- flags是一些参数,eg:flags=re.I表明忽略大小写
import re
input = "hello, lockeCucumber"
output = re.sub(r"locke\w+ber", "lucy", input)
print output # hello, lucy
re.sub参数repl使用函数
def _trans_to_date(matched):
delta_days = int(matched.group("delta_days"))
today = dtime.date.today()
date = today - dtime.timedelta(delta_days)
return "'{}'".format(str(date))
before_sql = "SELECT intersect_count(a, b, [$p0d, $p1d, $p2d] AS count_id FROM s"
sql = re.sub("\$p(?P<delta_days>\d+)d", _trans_to_date, sql)
print sql # SELECT intersect_count(a, b, ['2018-06-17', '2018-06-16', '2018-06-15'] AS count_id FROM slices
re中match,group的简单使用
根据写过的代码改个例子,具体理论后续补充吧
input = "lockeCucumber.[lucy]"
m = re.match(r"lockeCucumber\.\[(?P<person>\w+)\]", input)
if m:
love_person = m.group('person')
print love_person # lucy
网友评论