用于从 HTML 元素中捕获标记的正则表达式 [重复]

Posted

技术标签:

【中文标题】用于从 HTML 元素中捕获标记的正则表达式 [重复]【英文标题】:RegEx for capturing a token from an HTML element [duplicate] 【发布时间】:2019-10-11 13:26:00 【问题描述】:

所以我试图从 html 中的对象中获取一个值。我已经找到了获取价值的方法,但是添加了一些我不想要的额外内容。

我尝试过使用 .split() 和组,但它们都没有做任何事情。

html = r.text
checkouttoken = re.search('DF_CHECKOUT_TOKEN = (.*?);', html, re.S)

print(checkouttoken.group(0))

预期:

27f37949bb8a76ede81508c8c1b750c8

实际:

< iframe srcdoc="&lt;script&gt;!function()var e=function(e)var t=exports:;return e.call(t.exports,t,t.exports),t.exports,r=function()fun
DF_CHECKOUT_TOKEN = "27f37949bb8a76ede81508c8c1b750c8";

【问题讨论】:

【参考方案1】:

group(1)group(0) 是所有匹配的文本,group(1) 是您捕获的第一个组。

此外,如果您不希望结果中出现引号,则需要将引号添加到捕获组之外的正则表达式:'DF_CHECKOUT_TOKEN = "(.*?)";'

【讨论】:

谢谢,但这不是我想要的。我希望隔离结帐令牌并留下多余的位。 我自己搞定了,我拆分了字符串。无论如何,谢谢!【参考方案2】:

这里我们可能想要的表达式可以很简单:

DF_CHECKOUT_TOKEN = \"(.+?)\"

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"DF_CHECKOUT_TOKEN = \"(.+?)\""

test_str = "< iframe srcdoc=\"<script>!function()var e=function(e)var t=exports:;return e.call(t.exports,t,t.exports),t.exports,r=function()fun DF_CHECKOUT_TOKEN = \"27f37949bb8a76ede81508c8c1b750c8\";"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match matchNum was found at start-end: match".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group groupNum found at start-end: group".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Demo

【讨论】:

以上是关于用于从 HTML 元素中捕获标记的正则表达式 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

修改正则表达式模式以将嵌套标记捕获到对象数组中

正则表达式捕获带有类名的 html 元素

Perl 中的正则表达式组:如何从正则表达式组中捕获与字符串中出现的未知数量/多个/变量匹配的元素到数组中?

正则表达式删除所有空的 HTML 标记

正则表达式从 IBAN 捕获 BBAN?

用于在 = 和 ; 之间捕获单词的正则表达式