使用正则表达式解析字符串 python3

Using regex to parse string python3

我正在尝试从以下字符串访问 gSecureToken

$("#ejectButton").on("click", function(e) {
            $("#ejectButton").prop("disabled", true);
            $.ajax({
                url : "/apps_home/eject/",
                type : "POST",
                data : { gSecureToken : "7b9854390a079b03cce068b577cd9af6686826b8" },
                dataType : "json",
                success : function(data, textStatus, xhr) {
                    $("#smbStatus").html('');
                    $("#smbEnable").removeClass('greenColor').html('OFF');
                    showPopup("MiFi Share", "<p>Eject completed. It is now safe to remove your USB storage device.</p>");
                },
                error : function(xhr, textStatus, errorThrown) {
                    //undoChange($toggleSwitchElement);
                    // If auth session has ended, force a new login with a fresh GET.
                    if( (xhr.status == 401) || (xhr.status == 403) || (xhr.status == 406) ) window.location.replace(window.location.href);
                }
            });

如何使用正则表达式解析字符串中的值?我知道一旦我解析了它,我就可以将它加载为 JSON。

我当前的代码不使用正则表达式,它只是处理使用 BeautifulSoup 来解析一些 html。到目前为止,这是我的代码:

from bs4 import BeautifulSoup

class SecureTokenParser:

    @staticmethod
    def parse_secure_token_from_html_response(html_response):
        soup = BeautifulSoup(html_response, 'html.parser')
        for script_tag in soup.find_all("script", type="text/javascript"):
            print(script_tag)

我知道这并不多,但我认为将内容打印到终端是一个很好的起点。如何使用正则表达式解析 gSecureToken 然后将其加载为 JSON?

您不会向我们展示 print() 显示的内容,但可以想象它类似于下面的 s

用这个来解析它:

import re


def parse_token(s: str):
    token_re = re.compile(r'"gSecureToken": "(\w{40})"')
    m = token_re.search(s)
    return m.group(1)


s = '{"url": "/apps_home/eject/", "type": "POST", "data": {"gSecureToken": "7b9854390a079b03cce068b577cd9af6686826b8"}, "dataType": "json"}'
print(parse_token(s))
print(dict(data=dict(gSecureToken=parse_token(s))))

如果固定的 40 个字符限制太多,请随意使用 \w+。 手册页位于:https://docs.python.org/3/library/re.html

您的“...然后将其加载为 JSON?”评论似乎不相关, 因为通过要求我们用正则表达式解析它看起来没有 JSON 需要处理的剩余解析任务。 (我可能从一开始就从 json.loads() 开始, 而不是使用正则表达式,因为数据似乎是 JSON 格式。)

非正则表达式、非 BS4 选项:

html_response = [your string above]

splt = html_string.split(' : { ')
splt[1].split('},\n')[0]

输出:

'gSecureToken : "7b9854390a079b03cce068b577cd9af6686826b8" '

不需要回复BeautifulSoup这样的大包裹;您可以仅使用 Python re 包轻松解析出 gSecureToken 的值。

我假设您只想解析 gSecureToken 的值。然后,您可以创建一个正则表达式模式:

import re

pattern = r'{\s*gSecureToken\s*:\s*"([a-z0-9]+)"\s*}'

然后,我们可以使用,例如,您的测试字符串:

test_str = """
$("#ejectButton").on("click", function(e) {
            $("#ejectButton").prop("disabled", true);
            $.ajax({
                url : "/apps_home/eject/",
                type : "POST",
                data : { gSecureToken : "7b9854390a079b03cce068b577cd9af6686826b8" },
                dataType : "json",
                success : function(data, textStatus, xhr) {
                    $("#smbStatus").html('');
                    $("#smbEnable").removeClass('greenColor').html('OFF');
                    showPopup("MiFi Share", "<p>Eject completed. It is now safe to remove your USB storage device.</p>");
                },
                error : function(xhr, textStatus, errorThrown) {
                    //undoChange($toggleSwitchElement);
                    // If auth session has ended, force a new login with a fresh GET.
                    if( (xhr.status == 401) || (xhr.status == 403) || (xhr.status == 406) ) window.location.replace(window.location.href);
                }
            });
"""

最后我们可以搜索正则表达式的测试字符串:

match = re.search(pattern, test_str)
matching_string = match.groups()[0]
print(matching_string)

这给了我们想要的值:

7b9854390a079b03cce068b577cd9af6686826b8

您可以通过访问此 link 了解此正则表达式的工作原理:www.regexr.com/4ihpd