python - 贪婪的正则表达式回顾

标签 python regex

<分区>

我正在编写一个正则表达式来获取 "" 之间的数据.我遇到的唯一问题是最后一个 "正在被捕获。 Regex

  line = '<DT><A HREF="https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html" ADD_DATE="1567455957">Clickjacking Defense · OWASP Cheat Sheet Series</A>'
  capture_regex = re.compile(r'(?<=HREF=").*?"',re.IGNORECASE)
  m = capture_regex.search(line)

m.group()版画 https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html" .如何编写不包含最后一个引号的正则表达式。

回答了我的问题。我补充说我在我的正则表达式中添加了所谓的非贪婪。 capture_regex = re.compile(r'(?<=HREF=").*?(?=")',re.IGNORECASE) .通过添加 ?* 之后让它只停在第一个 " .

最佳答案

也许,来自 bs4 的 find_all 可能工作正常:

from bs4 import BeautifulSoup

line = '<DT><A HREF="https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html" ADD_DATE="1567455957">Clickjacking Defense · OWASP Cheat Sheet Series</A>'
soup = BeautifulSoup(line, 'html.parser')

for l in soup.find_all('a', href=True):
    print(l['href'])

输出

https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html

如果不是,也许,一些类似的表达

(?i)href="\s*([^\s"]*?)\s*"

with re.findall 可能在这里工作:

import re

expression = r'(?i)href="\s*([^\s"]*?)\s*"'

string = """
<DT><A HREF="https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html" ADD_DATE="1567455957">Clickjacking Defense · OWASP Cheat Sheet Series</A>
<DT><A HREF=" https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html " ADD_DATE="1567455957">Clickjacking Defense · OWASP Cheat Sheet Series</A>
"""

print(re.findall(expression, string))

输出

['https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html', 'https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html']

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


关于python - 贪婪的正则表达式回顾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862700/

相关文章:

python - 为什么 lambda 函数以不同的方式从 dict.items() 和元组列表中获取数据?

Python - 如何从 __init__ 方法中引用类变量或方法?

regex - 用于 git 合并冲突的 Vim 正则表达式

php - preg_match 给出的公式和字符?

python - 在 Django 中编辑表单创建新实例

python - 如何提取处于隐藏可见性模式的文本?

python - 过滤 pandas .isnull().any() 输出

python - 如何从 pandas 数据框中使用正则表达式删除答案中的点号 : '(i)' , '(ii)' 、 '(iii)' ?

c# - 使用正则表达式匹配字符串 c#

javascript - 正则表达式替换字符串的一部分