Reputation: 14990
I have a python program that calls sed
as follows.
url = os.system("sed 's/.*proxy=\([^&]*\).*/\1/' message")
message is a variable containing some data.I think sed expects a file in that place. How is this usually done in python
Upvotes: 0
Views: 396
Reputation: 247
E.g.
message = 'asdf proxy=127.0.0.1 fdsa'
re.sub('.+proxy=([^& ]*).*', r'\1', message)
yields
127.0.0.1
Be aware of greedy vs. non-greedy matching at the beginning of your regex.
Upvotes: 1
Reputation: 881623
Python comes with its own internal regex engine, which would be preferable, especially since the return code from os.system()
is the exit code of the program rather than its standard output.
It also helps with portability since calling an external executable may not work on all systems (Windows has no sed
by default).
For details, look into re.sub
:
import re
url = 'http://xyzzy.com?paxdiablo=awesome'
url = re.sub(r'^[^?]*\?','',url)
url = re.sub(r'=',' is ',url);
print url
Or re.findall
:
import re
url = 'http://xyzzy.com?Python=fantastic&paxdiablo=still%20awesome'
args = re.findall(r'[?&]([^?&]*=[^?&]*)', url)
for arg in args:
(object,property) = arg.split("=")
print object, "is", property.replace('%20',' ')
Or many of the other methods found in the re
module for Python 2 or Python 3.
Upvotes: 5