在Python中使用Regex查找子串?

时间:2016-03-24 10:25:47

标签: python regex

我有一个字符串:

line_to_test = "http://website/[SequenceOfLetters&NumbersONLY].html"

我想要一个正则表达式来匹配上面的模式:

我目前所尝试的是:

c = len(re.findall(r"http:\/\/website\/([a-zA-Z0-9]?).html",line_to_test))

但即使c包含模式,line_to_test也会变为空。

2 个答案:

答案 0 :(得分:1)

?表示在此之前是可选的,在这种情况下[a-zA-Z0-9]。这意味着您可以使用01次字母或数字。

您应该使用*,选择0次或更多次,或使用+选择它1次或更多次。

试试这个RegEx:

c = len(re.findall(r"http:\/\/website\/([a-zA-Z0-9]+).html",line_to_test))

如果您使用的是*,则它与([a-zA-Z0-9]+)?相同,这意味着http://website/.html会起作用。

Live Demo on RegExr

答案 1 :(得分:0)

?只匹配0或1个字符。试试

c = len(re.findall(r"http:\/\/website\/([a-zA-Z0-9]+).html",line_to_test))

您可以使用regexr等在线服务来测试您的正则表达式:http://regexr.com/3d301

相关问题