【发布时间】:2015-11-25 04:04:39
【问题描述】:
我想在 python 2.7 之后找到一个 1 到 6 位数字的主题标签,但我的正则表达式不正确匹配。
这是我的例子:
chaine = "[url=http://forum.darkgyver.fr/t27142-probleme-boitier-papillon-faisceau#265132:<UID>]http://forum.darkgyver.fr/t27142-probleme-boitier-papillon-faisceau#265132[/url:<UID>]"
regex = re.compile('http://forum.darkgyver.fr/(.*)\#(\d{1-6})')
match = regex.search(chaine)
if match:
pos1 = match.start()
pos2 = match.end()
else:
pos1 = -1
pos2 = -1
print "pos1 %d" % pos1
print "pos2 %d" % pos2
url_tempo = chaine[pos1:pos2]
print "url_tempo %s" % url_tempo
posPost = pos1 + url_tempo.find('#') + 1
numPost = chaine[posPost:pos2]
print "numPost %s" % numPost
第一个正则表达式返回“不匹配”。也许主题标签没有正确声明。
所以我改变了我的正则表达式如下:
regex = re.compile('http://forum.darkgyver.fr/(.*)\#([0-9]+(:| | |\n|\[|$))')
匹配错误位置pos2=161应该是pos2=80
如何将我的正则表达式修复到主题标签和后面的 1 到 6 位数字?
【问题讨论】:
-
\d{1,6}......不是\d{1-6} -
感谢马丁的第一个回答。我试过 regex = re.compile('forum.darkgyver.fr(.*)\#(\d{1,6})') 部分匹配,pos2 应该是“80”而不是“160”,numpost 没有包含好的字符串应该只有 "265132" pos2=160 numPost 265132:
]forum.darkgyver.fr/…
标签: python regex python-2.7 hashtag digit