在这个python字符串模式匹配中,我想过滤掉s1,它应该像*\2017-01-23\,日期字符串后跟一个'\'。知道吗?
s1="historyDataxxn3_1010366372_2017-01-25_1126807";
s2="historyDataxx2017-01-23n3_1010366372_2017-01-25_1126807";
date_reg_exp = re.compile('d{4}[-/]d{2}[-/]d{2}\');
mat = re.match(date_reg_exp, s)
if mat is not None:
print("not matched")
else:
print("matched")
使用search
而不是match
这是文档所说的
Python 提供了两种不同的基于常规的原始操作 表达式:re.match() 仅在 字符串,而 re.search() 检查 字符串(这是Perl默认做的)。
提供的字符串具有无效的转义x
。要将它们用作行字符串,您可以使用 r"string" 。s1
和s2
变量写为
s1=r"historyDataxxn3_1010366372_2017-01-25_1126807"
s2=r"historyDataxx2017-01-23n3_1010366372_2017-01-25_1126807"
您可以按如下方式重写函数。
import re
def containsDate(s):
date_reg_exp = re.compile(r'(d{4}-d{2}-d{2})')
mat = re.search(date_reg_exp,s)
return mat is not None
现在函数可以按如下方式使用
s1=r"historyDataxxn3_1010366372_2017-01-25_1126807"
s2=r"historyDataxx2017-01-23n3_1010366372_2017-01-25_1126807"
if containsDate(s1):
print "match"
else:
print "no match"
您必须使用原始字符串而不是字符串。因为xx
不是一个公认的角色。
a = "xx"
会抛出ValueError: invalid x escape
您可以像这样尝试:
import re
s1 = r"historyDataxxn3_1010366372_2017-01-25_1126807"
s2 = r"historyDataxx2017-01-23n3_1010366372_2017-01-25_1126807"
s = r"(?:.*?\)(d+-d+-d+)(?:\.*)$"
reg = re.compile(s)
print re.match(reg, s1)
print re.match(reg, s2).group(1)
输出:
None
2017-01-23