Reputation: 565
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 !
Upvotes: 2
Views: 69
Reputation: 567
For other strings,
Try out this https://regex101.com/r/zwI2Mk/1 and https://regex101.com/r/zwI2Mk/1/codegen?language=python
Upvotes: 0
Reputation: 81684
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']
Upvotes: 2