views:

70

answers:

3

I have a string of the form "foo-bar-1.23-4", and I need to split at the first hypen followed by a numeral, such that the result is ['foo-bar', '1.23-4']. I've tried the following:

>>> re.split('-\d', 'foo-bar-1.23-4', 1)
['foo-bar', '.23-4']

and

>>> re.split('-(\d)', 'foo-bar-1.23-4', 1)
['foo-bar', '1', '.23-4']

with suboptimal results. Is there a one-liner that will get me what I want, without having to munge the delimiter with the last element?

+1  A: 

You were very close, try this:

re.split('-(?=\d)', 'foo-bar-1.23-4', 1)

I am using positive lookahead to accomplish this - basically I am matching a dash that is immediately followed by a numeric character.

Andrew Hare
A: 
re.split('-(?=\d)', 'foo-bar-1.23-4', 1)

Using lookahead, which is exactly what Andrew did but beat me by a minute... :-)

David Johnstone
A: 

Would a positive lookahead work?

re.split('-?=\d', 'foo-bar-1.23-4', 1)

Not sure if you need the ( and the ) surrounding the lookahead, but give it a shot.

Adrian Lynch