Ryan Garnet Andrianto
Ryan Garnet Andrianto

Reputation: 23

Regex to extract items from list

I have a string with specific format and I'd like to extract its data into python array. What is the regEX string format for this?

The string

417,364.4265,2535.2258,16.7616,143.5451,0,0 ; Leviathan

Array

arr = ['417', '364.4265', '2535.2258', '16.7616', '143.5451', '0', '0', 'Leviathan']

Upvotes: 1

Views: 171

Answers (3)

Hugo Barbosa
Hugo Barbosa

Reputation: 1

if U can add space between the numbers U can use the split method

s=417 364.4265 2535.2258 16.7616 143.5451 0 0 Leviathan
s=s.split()

output:

['417','364.4265','2535.2258','16.7616','143.5451','0','0','Leviathan']

it's easier and U don' need to put extra libraries

Upvotes: 0

Jan
Jan

Reputation: 43169

You could use

import re

string = "417,364.4265,2535.2258,16.7616,143.5451,0,0 ; Leviathan"
rx = re.compile(r'([^,;\s]+)')
output = rx.findall(string)
print(output)

Which yields

['417', '364.4265', '2535.2258', '16.7616', '143.5451', '0', '0', 'Leviathan']

Upvotes: 0

yatu
yatu

Reputation: 88236

You could use re.split with the to split on multiple separators:

import re
s  ='417,364.4265,2535.2258,16.7616,143.5451,0,0 ; Leviathan'

re.split(r' *[,;] *',s)
# ['417', '364.4265', '2535.2258', '16.7616', '143.5451', '0', '0', 'Leviathan']

Upvotes: 1

Related Questions