Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching multiple groups in string

Tags:

python

regex

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

like image 256
Shraddha Avatar asked Dec 01 '25 09:12

Shraddha


1 Answers

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.

like image 98
Rohit Jain Avatar answered Dec 02 '25 23:12

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!