Reputation: 2579
I have a string like 'testname=ns,mem=2G'
After parsing the above string I want
to assign a variable tstnm
to ns
and variable memory
to 2G
import re
str = "testname=ns,mem=2G"
b = re.search('(?<=testname=)\w+', str)
m = re.search('(?<=mem=)\w+', str)
if b:
tstnm = b.group(0)
if m:
memory = m.group(0)
which works , but then when I tried to do it in one go , like -
m = re.search('(?<=testname=)(\w+)\,(?<=mem=)(\w+)', str)
m
is None
//
Upvotes: 3
Views: 86
Reputation: 239443
Should you be using regex for this? How about simple string operations
inputString = "testname=ns,mem=2G"
result = inputString.split(",")
tstnm = result[0].split("=")[1]
memory = result[1].split("=")[1]
print tstnm, memory
Output
ns 2G
Upvotes: 1
Reputation: 92976
That is because you are using lookaround assertions. They do only match a position, but not the string inside the groups. So, with \,(?<=mem=)(\w+)
you are creating a regex that can never be true, because \,(?<=mem=)
is always false.
You could use capturing groups instead:
import re
input = "testname=ns,mem=2G"
result = re.search('testname=(\w+),mem=(\w+)', input)
if result:
tstnm = result.group(1)
memory = result.group(2)
Upvotes: 3
Reputation: 213213
Use re.findall()
, and you can merge your regex using pipe(|)
:
>>> s = "testname=ns,mem=2G"
>>> re.findall('(?<=testname=)\w+|(?<=mem=)\w+', s)
['ns', '2G']
Don't use str
as variable name.
Upvotes: 4