簡體   English   中英

如何使用正則表達式或任何其他方法對字符串的特定模式進行子處理(python 2.7)?

[英]How can I use regular expression or any other method to sub a specific pattern of a string (python 2.7)?

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

現在,網址中的參數rand不斷變化,並且始終為5個數字,因此可以為rand=1234599999

現在我想在這種情況下( 'rand=52710' )更改為'sub'或僅僅是''

我已經通過使用https://developers.google.com/edu/python/regular-expressions進行了嘗試,但沒有提出可靠的解決方案

任何幫助,將不勝感激謝謝。

使用正則表達式

例如:

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

如果沒有正則表達式,則假設您的聲明“ 現在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.

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