簡體   English   中英

Python 正則表達式替換整個單詞,包括一些特殊字符

[英]Python Regex to replace whole word including some special characters

我是正則表達式的新手,想知道如何實現以下內容。 例如,我有一個帶有url('Inter.ttf')的 css 文件,我的 python 程序會將此 url 轉換為url('user/Inter.ttf')

但是,當我嘗試避免雙重替換時遇到了問題。 那么在使用 re.sub 替換它們時,如何使用正則表達式告訴 python url('Inter.ttf')url('/hello/Inter.ttf')之間的區別。

我試過re.sub(r"\boriginalurl.ttf\b", "/user/" + originalurl.ttf, file) 但這似乎行不通。

那么我如何告訴 python 用'/user/Inter.ttf''/hello/Inter.ttf'替換整個單詞'Inter.ttf' ' 和 ' '/user/hello/Inter.ttf'

您可以使用look-around方法動態插入/user/

(?<=url\(')/*(?=(?:.*?Inter\.ttf)'\))

然后使用re.sub替換為/user/

strings = ["url('Inter.ttf')", "url('/hello/Inter.ttf')"]

p = re.compile(r"(?<=url\(')/?(?=(?:.*?Inter\.ttf)'\))")

for s in strings:
    s = re.sub(p, "/user/", s)
    print(s)
url('user/Inter.ttf')
url('user/hello/Inter.ttf')

模式說明

(?<=url\(') : Positive lookbehind; 匹配像url('這樣的字符串之后的字符串。

/? : 匹配個或一個正斜杠/ 這對於匹配/hello/Inter.ttf之類的路徑很重要,因為它以/開頭。 這將被選中並替換為替換字符串/user/中的結尾正斜杠。

(?=(?:.*?Inter.ttf)'\) :正向前瞻; 匹配以Inter.ttf')結尾的字符串之前的字符串。

我建議在https://regex101.com上使用它,選擇左側的Substitution方法。

編輯

如果要匹配多個 fonts,只需刪除正則表達式的Inter.ttf部分:

(?<=url\(')/?(?=(?:.*?)'\))

或者,如果您希望將 append /user/替換為具有文件擴展名的路徑,您可以將Inter\.ttf替換為\.\w{3} ,它有效匹配[a-zA-Z0-9_]

(?<=url\(')/?(?=(?:.*?\.\w{3})'\))

沒有正則表達式的簡單方法是這樣的:

fin = open("input.css", "rt")
fout = open("out.css", "wt")
for line in fin:
    if "'Inter.ttf'" in line:
        fout.write(line.replace("'Inter.ttf'", "'/user/Inter.ttf'"))
    elif "'/hello/Inter.ttf'" in line:
        fout.write(line.replace("'/hello/Inter.ttf'", "'/user/hello/Inter.ttf'"))
    else:
        fout.write(line)

暫無
暫無

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

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