正则表达式匹配

2024-06-06 20:00:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手(我也没有任何编程培训),所以在我提问时请记住这一点。

我正在尝试搜索检索到的网页,并使用指定的模式查找所有链接。我已经在其他脚本中成功地完成了这个任务,但是我得到了一个错误,上面说

raise error, v # invalid expression

sre_constants.error: multiple repeat

我不得不承认,我不知道为什么,但我还是对Python和正则表达式很陌生。但是,即使我不使用模式并使用特定链接(只是为了测试匹配),我也不相信我返回任何匹配项(打印match.group(0)时不会向窗口发送任何内容)。我测试的链接在下面被注释掉了。

有什么想法吗?以身作则对我来说通常比较容易,但是你能给我的任何建议都是非常感激的!

布洛克

import urllib2
from BeautifulSoup import BeautifulSoup
import re

url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)

pattern = r'<a href="http://forums.epicgames.com/archive/index.php?t-([0-9]+).html">(.?+)</a> <i>((.?+) replies)'
#pattern = r'href="http://forums.epicgames.com/archive/index.php?t-622233.html">Gears of War 2: Horde Gameplay</a> <i>(20 replies)'

for match in re.finditer(pattern, page, re.S):
    print match(0)

Tags: importrecomhttpindex链接htmlmatch
3条回答

这意味着正则表达式有错误。

(.?+)</a> <i>((.?+)

怎么办?+意思是?两者都有?和+是元字符,彼此之间没有意义。也许你忘了逃走或者别的什么。

你需要转义字面上的“?”以及要匹配的文本“(”和“)”。

还有,不是'?+,我认为您正在寻找由“+?”提供的非贪婪匹配。

More documentation here.

对于您的情况,请尝试以下操作:

pattern = r'<a href="http://forums.epicgames.com/archive/index.php\?t-([0-9]+).html"> (.+?)</a> <i>\((.+?) replies\)'
import urllib2
import re
from BeautifulSoup import BeautifulSoup

url = "http://forums.epicgames.com/archive/index.php?f-356-p-164.html"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)

# Get all the links
links = [str(match) for match in soup('a')]

s = r'<a href="http://forums.epicgames.com/archive/index.php\?t-\d+.html">(.+?)</a>' 
r = re.compile(s)
for link in links:
    m = r.match(link)
    if m:
        print m.groups(1)[0]

相关问题 更多 >