haji haji - 1 year ago 82
Python Question

splitting string using regular expression in python

Hi guys I want to split the following string that are parsed from a text file using perhaps regular expression in python.

Inside the text file(filename.txt)


I want a function that when looping through arrayOfStrings wii split it so that the following is displayed



This is what I have done so far

import re
pattern = '(?<!\d)[\.=]|[\.=](?!\d)'

f = open('filename.txt','rb')
for line in data_file:
str_values = re.split(pattern, line.rstrip())
print str_values

This is what is being printed

['iPhone', 'Case', '1', 'left', '1099.0.2']
['new', 'phone', 'newwork', 'bla', 'jpg']

but I want the last array to be


Answer Source

If you have regular enough input data that you can always split first at the = character, then split the first half at every . character, I would skip regex entirely, as it is complicated and not very pretty to read.

Here's an example of doing just that:

s = 'new.phone.newwork=bla.jpg'
l = str.split(s.split('=')[0], '.') + s.split('=')[1:]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download