简体   繁体   中英

Search and replace multiple patterns in a string in python script

I am attempting to create a python script that does the following:

  1. Prompts the user to input a string
  2. Strip all characters from 'hxxps://' to 'u='
  3. Replace 'hxxp-3A__' with 'http://'
  4. Replace all '_' with '/'
  5. Delete all characters from '&d=' to the end of the string(including &d)

Example of the string the user would be prompted to enter to be decoded:

<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>

What the output should look like:

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

I've tried various combinations of the following script but can't seem to search/replace more than 1 string(http-3a__ for http://). My last script attempt included the following:

!/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);

Please help!!!

Regarding your first example with the Apple URL, this code works:

#!/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

You can do something like

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

you can use replace this is the syntax:

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

so for you it would by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM