猿问

正则表达式搜索特定的文本结构

我想在字符串中查找某个结构的所有结果,最好使用正则表达式。

要查找所有网址,可以使用

re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', decode)

它返回

 'https://en.wikipedia.org'

我想要一个正则表达式字符串,它可以找到:

href="/wiki/*anything*"


ITMISS
浏览 226回答 1
1回答

尚方宝剑之说

OP:开头必须是 href="/wiki/ 中间可以是任何内容,结尾必须是 "st = "since-OP-did-not-provide-a-sample-string-34278234$'blahhh-okay-enough.href='/wiki/anything/everything/nothing'okay-bye"&nbsp; &nbsp;&nbsp;print(st[st.find('href'):st.rfind("'")+1])输出:href='/wiki/anything/everything/nothing'编辑:如果我们要解析可能的 html,我会选择 BeautifulSoup 。from bs4 import BeautifulSouptext = '''<a href='/wiki/anything/everything/nothing'><img src="/hp_imgjhg/411/1/f_1hj11_100u.jpg" alt="dyufg" />well wait now <a href='/wiki/hello/how-about-now/nothing'>'''soup = BeautifulSoup(text, features="lxml")for line in soup.find_all('a'):&nbsp; &nbsp; print("href =",line.attrs['href'])输出:href = /wiki/anything/everything/nothinghref = /wiki/hello/how-about-now/nothing
随时随地看视频慕课网APP

相关分类

Python
我要回答