簡體   English   中英

使用正則表達式解析字符串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

您可以通過以下鏈接查看此正則表達式為何起作用:www.regexr.com/4ihpd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM