【问题标题】:RegEx for capturing a token from an HTML element [duplicate]用于从 HTML 元素中捕获标记的正则表达式 [重复]
【发布时间】: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";

【问题讨论】:

    标签: python regex regex-lookarounds regex-group regex-greedy


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      相关资源
      最近更新 更多