[英]Why can't my regular expression find the result?
The data is like this: 数据是这样的:
post date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'
and here is my code for the task: 这是我的任务代码:
p1 = re.compile(r"post date")
m1 = p1.search(postline)
if m1:
month = re.search(r'post date="([\d\W]+)"', postline).group(1)
You're searching for double qoutes "
whereas your example is with single qoutes '
. 你正在寻找双qoutes "
而你的例子是单qoutes '
。
re.search(r'post date="([\d\W]+)"'
^ ^
. 。
post date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'
^ ^
Edit: The problem is no longer within the regex but your python. 编辑:问题不再是正则表达式,而是你的python。 Here's an example: 这是一个例子:
import re
postline = "post date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'"
pattern = "post date='([\d\W]+)'"
p1 = re.compile(pattern)
date = p1.search(postline).group(1)
print date
Outputs: 输出:
2008-7
Will your date always be in the format YYYY-M
? 您的约会日期是否格式YYYY-M
? If so, construct your pattern accordingly? 如果是这样,相应地构建您的模式? This pattern allows for YYYY-M
or YYYY-MM
: 此模式允许YYYY-M
或YYYY-MM
:
>>> import re
>>> postline = "post date='2008-7' postCount='8' viewCount='24308' questionCount='5' answerCount='76' answeredQuestion='5'"
>>> pat = r"post date='(\d{4}-\d{1,2})'"
>>> re.search(pat, postline).group(1)
'2008-7'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.