【问题标题】:How can I use regular expression or any other method to sub a specific pattern of a string (python 2.7)?如何使用正则表达式或任何其他方法来子字符串的特定模式(python 2.7)?
【发布时间】:2018-05-15 12:16:55
【问题描述】:

所以我的字符串 url 是'http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112'。这是在 python 2.7 中。

现在 url 中的参数 rand 一直在变化,并且始终是 5 个数字长度,因此它可以是 rand=1234599999

现在我想在这种情况下将其 ('rand=52710') 更改为 'sub' 或只是 ''

我已经尝试过使用https://developers.google.com/edu/python/regular-expressions,但没有找到可靠的解决方案

任何帮助将不胜感激。

【问题讨论】:

  • @FHTMitchell 为什么我投了反对票?
  • 哦,也许吧,但我做了几次尝试......我在这里阅读了https://developers.google.com/edu/python/regular-expressions,并提出了match = re.search(r'rand=\d\d\d\d\d', url).group()的解决方案

标签: python regex string replace


【解决方案1】:

使用正则表达式

例如:

import re
u = 'http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112'
print re.sub("rand\=\d+", "SUB", u)

输出:

http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&SUB&w=400&h=112

【讨论】:

  • 我们是否应该直接给出答案而不尝试(+1)?
  • 对不起,我只是在练习堆栈溢出。
【解决方案2】:

如果没有正则表达式,假设您的声明“现在 url 中的参数 rand 不断变化,并且始终是 5 个数字长度,因此它可以是 rand=12345 或 99999”成立:

url = "http://helloworld.net/b/c/3?csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112"
index = url.rfind("rand=")
if index != -1:
    url = url[:index] + url[index+11:]  # add 'sub' between url parts if you want it
# http://helloworld.net/b/c/3?csid=fire.clan.com/gram/&din=&w=400&h=112

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2019-12-25
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多