簡體   English   中英

在python腳本中搜索並替換字符串中的多個模式

[英]Search and replace multiple patterns in a string in python script

我正在嘗試創建執行以下操作的python腳本:

  1. 提示用戶輸入字符串
  2. 將所有字符從'hxxps://''u='
  3. 'hxxp-3A__' with 'http://'替換'hxxp-3A__' with 'http://'
  4. 將所有'_'替換為'/'
  5. 刪除所有從'&d='到字符串末尾的字符(包括&d)

將提示用戶輸入要解碼的字符串示例:

<b>hxxps://emailfiltervendor.com/v2/url?u=</b>hxxp-3A__developer.apple.com_contact<b>_&d=AAMC-Q&c=zQ6tLaF7dShu6emFdFLQLQ&r=Omg3VPeUzekjh8aAoyWWiIblQyDVxual9qHMwJiqOpQ&m=MtC66x1fgSnrN9foA74EcYf6Ekmp0vmUDRLTGVtTQcU&s=xHGspXPb32hmzbF1rkJ2jWRvS011WqvwsU1LSM4zQdU&e=</b>

輸出應如下所示:

hxxp://developer.apple.com/contact/

我嘗試了以下腳本的各種組合,但似乎無法搜索/替換多個字符串(http://的http-3a__)。 我上一次的腳本嘗試包括以下內容:

!/usr/bin/python
import re

str = "http-3A__camcogm.com_americanexpress.com&d=AAICaQ&c=zQ6tLaF7dShu6emFdFLQLQ&r=AfgFWq3_k20u3QSxhfE-TPsRXxWcDPc0YcZAhO55eV0&m=S_APJ9UeCnO7zAnBcvb2jKu_XvZJkrzyy0N$

print re.sub("http-3A__", "http://", str), ("&d*.*"," ", str);   
print re.sub("&d*.*"," ", str);

請幫忙!!!

關於Apple URL的第一個示例,此代碼有效:

#!/usr/bin/env python

import re

string = "hxxp-3A__developer.apple.com_contact_&d=AAMC-Q&c=zQ6tLaF7dShu6emFdFLQLQ&r=Omg3VPeUzekjh8aAoyWWiIblQyDVxual9qHMwJiqOpQ&m=MtC66x1fgSnrN9foA74EcYf6Ekmp0vmUDRLTGVtTQcU&s=xHGspXPb32hmzbF1rkJ2jWRvS011WqvwsU1LSM4zQdU&e="

string = string.replace('hxxps://',"u=")
string = string.replace('hxxp-3A__','http://')
string = string.replace('_','/')
string = re.sub(r'&d=[\s\S]*','',string)

print string

你可以做類似的事情

>>> val=re.sub(r'hxxps.*u=hxxp-3A__([^&]+).*', r'hxxp://\1', str)
>>> re.sub(r'_', '/', val)
'hxxp://developer.apple.com/contact/'

您可以使用replace這是語法:

string.replace(str ,old, new[, max])

所以對你來說

import string
str = "your text"
string.replace('str'hxxp-3A__','http://')
string.replace('str','_' , '/' )
sep = "&d="
str.split(sep, 1)[0]
str = str(0)

暫無
暫無

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

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