簡體   English   中英

如何查找和替換正則表達式代碼

[英]How to find and replace in a regex code

我正在嘗試查找並替換正則表達式代碼

<div class="gallery-image-container">
    <div jstcache="1116"
         class="gallery-image-high-res loaded"
         style="width: 396px;
                height: 264px;
                background-image: url(&quot;https://lh5.googleusercontent.com/p/AF1QipMcTfMPZj_d5iip9WKtN2SQB9Je5U4rRB0nT_t8=s396-k-no&quot;);
                background-size: 396px 264px;"
         jsan="7.gallery-image-high-res,7.loaded,5.width,5.height,5.background-image,5.background-size">
    </div>
</div>

在上面的代碼中,我使用了This

(https:\/\/[^&]*)

提取此URL

https://lh5.googleusercontent.com/p/AF1QipMcTfMPZj_d5iip9WKtN2SQB9Je5U4rRB0nT_t8=s396-k-no

我使用了此正則表達式s\\d{3}來獲取s396

現在我想將URL中的s396替換為s1000

現在是Stock,不知道該怎么做。

無論如何,請問所有這些都可以用一個正則表達式代碼而不是多個代碼完成嗎?

我建議使用HTML解析器,但我知道有時是不可能的。 這是python中的一個小例子。

import re

data = '''
<div class="gallery-image-container">
    <div jstcache="1116"
         class="gallery-image-high-res loaded"
         style="width: 396px;
            height: 264px;
            background-image: url(&quot;https://lh5.googleusercontent.com/p/AF1QipMcTfMPZj_d5iip9WKtN2SQB9Je5U4rRB0nT_t8=s396-k-no&quot;);
            background-size: 396px 264px;"
         jsan="7.gallery-image-high-res,7.loaded,5.width,5.height,5.background-image,5.background-size">
    </div>
</div>
'''
match = re.search("(https?://[^&]+)", data)
url = match.group(1)
url = re.sub("s\d{3}", "s1000", url)
print(url)

他們的關鍵部分是正則表達式

(https?://[^&]+)

它使用否定字符類。 就是說,使用可選的s://來查找http ,然后查找所有 &您可以使用此站點使用正則表達式:

https://regex101.com/r/b0APFA/1

我敢肯定,您可以做一個聰明的1班輪嵌套正則表達式來一次查找和替換所有內容,但是如果您有幾行內容,它將更容易進行故障排除。

暫無
暫無

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

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