【问题标题】:Python Regex to replace whole word including some special charactersPython正则表达式替换整个单词,包括一些特殊字符
【发布时间】:2021-02-09 04:04:54
【问题描述】:

我是正则表达式的新手,想知道如何实现以下内容。例如, 我有一个带有url('Inter.ttf') 的css 文件,我的python 程序会将此网址转换为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 替换整个单词 'Inter.ttf''/user/Inter.ttf''/hello/Inter.ttf''/user/hello/Inter.ttf'

【问题讨论】:

  • 尝试re.sub('^/?','/user/',file) 将导致Inter.ttf -> /user/Inter.ttf; /hello/Inter.ttf->/user/hello/Inter.ttfregex101.com/r/ntKFKy/1

标签: python regex


【解决方案1】:

您可以使用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')

模式说明

(?&lt;=url\('): 积极的向后看;匹配像url('这样的字符串之后的字符串。

/?:匹配 一个 正斜杠 /。这对于匹配像/hello/Inter.ttf 这样的路径很重要,因为它以/ 开头。这将被选中并替换为替换字符串中的结尾正斜杠/user/

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

我建议在https://regex101.com 上使用它,选择左侧的Substitution 方法。

编辑

如果你想匹配多种字体,你可以去掉正则表达式的Inter.ttf部分:

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

或者,如果您希望将/user/ 附加到具有文件扩展名的路径,您可以将Inter\.ttf 替换为\.\w{3},它有效地匹配[a-zA-Z0-9_] 中任意字符中的3 个:

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

【讨论】:

  • 感谢您的回复!但是如果列表是strings = ['Inter.ttf', '/hello/Inter.ttf', 'hello/Gothic.ttf', 'hello/GG.png', 'GG.png' ] 等,我将如何将'/user/' 附加到列表的所有元素中。
  • 感谢您的编辑。所以澄清一下,如果我想将它与 re.sub 一起使用以替换文件中的所有实例,我会输入 file = re.sub((?&lt;=url\(')/?(?=(?:.*?\.\w{3})'\)), '/user/', file) 吗?
  • @JongbinWon 是的,就是这样。确保在覆盖之前备份文件,以防万一出现问题!
  • 谢谢,这似乎有效。但是我遇到了一个小问题。如何确保正则表达式不会捕获诸如google.com 之类的网址?此外,我如何确保url(Inter.ttf)url('Inter.ttf') 都被正则表达式捕获。谢谢@gmdev
  • @Jongbin 将\w{3} 替换为(ttf|png)。使用| 就像说这个那个。现在它只会匹配具有ttfpng 的URL。请记住,此表达式中 | 的数量没有限制,因此您可以执行以下操作:(ttf|png|jpg|csv|txt)
【解决方案2】:

没有正则表达式的简单方法是这样的:

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)

【讨论】:

  • 我不认为它是单个字符串,而是整个 css 文件作为字符串 no?
  • 我们可以做一个文件简单的等待我更新它
  • 他想用 sub 来替换我相信的所有实例。使用 .replace 更难更慢
  • 我已经用 replace 完成了,你可以试试我更新代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多