Skip to main content
 首页 » 编程设计

python之在 Python 中使用正则表达式查找子字符串

2025年04月02日34bjzhanghao

我有一个字符串:

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

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

目前我尝试过的是:

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

但是即使 line_to_test 包含该模式,这里的 c 也会变为 null。

请您参考如下方法:

? 表示它前面的任何内容都是可选的,在本例中为 [a-zA-Z0-9]。这意味着您可以让一个字母或数字 0 或 1 次。

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

试试这个正则表达式:

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