[英]How can I use regular expression or any other method to sub a specific pattern of a string (python 2.7)?
So the string url I have is 'http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112'
. 所以我拥有的字符串网址是
'http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&rand=52710&w=400&h=112'
。 This is in python 2.7. 这是在python 2.7中。
Now the parameter rand in the url keeps changing and is always a 5 number length so it can be rand=12345
or 99999
and etc 现在,网址中的参数rand不断变化,并且始终为5个数字,因此可以为
rand=12345
或99999
等
Now I want to change that in this case ( 'rand=52710'
) to something like 'sub'
or just ''
现在我想在这种情况下(
'rand=52710'
)更改为'sub'
或仅仅是''
I have made attempts at this by using https://developers.google.com/edu/python/regular-expressions
but didn't come up with a solid solution 我已经通过使用
https://developers.google.com/edu/python/regular-expressions
进行了尝试,但没有提出可靠的解决方案
Any help would be appreciated thanks. 任何帮助,将不胜感激谢谢。
Using Regex . 使用正则表达式 。
Ex: 例如:
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)
Output: 输出:
http://helloworld.net/b/c/3?nw=174057&csid=fire.clan.com/gram/&din=&SUB&w=400&h=112
Without regex, assuming that your claim " now the parameter rand in the url keeps changing and is always a 5 number length so it can be rand=12345 or 99999 " holds true: 如果没有正则表达式,则假设您的声明“ 现在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.