2

Starting from "param1=1-param2=1.e-01-param3=A", how to get
["param1=1", "param2=1.e-01", "param3=A"] ? The problem is that the separator "-" may be contained in the value of a parameter.

Franck

>>> import re
>>> re.split("-", "param1=1-param2=1.e-01-param3=A")
['param1=1', 'param2=1.e', '01', 'param3=A']
>>> re.split("[^e]-[^0]", "param1=1-param2=1.e-01-param3=A")
['param1=', 'aram2=1.e-0', 'aram3=A']
>>> re.split("[?^e]-[?^0]", "param1=1-param2=1.e-01-param3=A")
['param1=1-param2=1.', '1-param3=A']

EDIT

OK, I forgot to mention param1, param2, param3 do actually not share the same "param" string. What about if we have to split "p=1-q=1.e-01-r=A"into the same kind of list ["p=1", "q=1.e-01", "r=A"] ?

EDIT

>>> re.split("(?:-)(?=[a-z]+)", "p=1-q=1.e-01-r=A")
['p=1', 'q=1.e-01', 'r=A']

Does the job for me as I know parameter names can not carry any -.

Thanks, guys !

2 Answers 2

2

By using non-capturing group and positive lookahead, capture '-' only if it is followed by 'param':

import re

string = "param1=1-param2=1.e-01-param3=A"
print(re.split(r"(?:-)(?=param)", string))
# ['param1=1', 'param2=1.e-01', 'param3=A']

Live demo on regex101

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I didn't know about non-capturing group and positive lookahead: still need to read on these notions. Could you detail a bit further the meaning of both (?:-) and (?=param) in this case ?
(?:-) will make sure the - isn't actually captured (otherwise the returned list would be ['param1=1', '-', 'param2=1.e-01', '-', 'param3=A'], and (?=param) will make sure to only capture '-' that have param after them (so - in a middle of a param value will not match)
0

For other strings,

Try out this https://regex101.com/r/zwI2Mk/1 and https://regex101.com/r/zwI2Mk/1/codegen?language=python

1 Comment

This will fail if a value is string that contains -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.