DanielSon
DanielSon

Reputation: 1545

Python Regex match 2nd or 3rd word in line

I'm trying to separate lines into 3 sections using regex, with a typical line fitting into this kind of pattern: -30.345 150.930 112.356

I'm extracting the first section of data fine using lat = float(re.match('[^\s]+', line).group(0)), but have been unable to correctly target the 2nd and 3rd numbers.

I've tried/am trying long = float(re.match('.*?\s(\S+)\s.*?', line).group(0)) but this is returning the entire string up until the 2nd whitespace. How can I target just the 2nd number and 3rd number in these strings?

Upvotes: 2

Views: 358

Answers (1)

anubhava
anubhava

Reputation: 785276

If you cannot do split then you can just match the numbers with optional - or + at the start:

>>> s = '-30.345 foo 150.930 abc 112.356 another .123'
>>> re.findall(r'([+-]?\d*\.?\d+)', s)
['-30.345', '150.930', '112.356', '.123']

RegEx Demo

Upvotes: 2

Related Questions