简体   繁体   中英

How to re.search() multiple patterns in python?

I have a list like this:

['t__f326ea56',
 'foo\tbar\tquax',
 'some\ts\tstring']

I want to get results in 4 different variables like this:

s1 = 't__f326ea56'
s2 = ['foo', 'some']
s3 = ['bar', 's']
s4 = ['quax', 'string']

Normally I could do a search like re.search(r'(.*)\\t(.*)\\t(.*)', lst).group(i) to get the s2, s3, s4. But I can't do simultaneous search for all 4. Is there any special option in re module that I can use?

Thanks

You can use the split() method in the re module:

import re

s = ['t__f326ea56',
'foo\tbar\tquax',
'some\ts\tstring']

new_data = [re.split("\\t", i) for i in s]
s1 = new_data[0][0]

s2, s3, s4 = map(list, zip(*new_data[1:]))

Output:

s1 = 't__f326ea56'
s2 = ['foo', 'some']
s3 = ['bar', 's']
s4 = ['quax', 'string']

Edit:

for lists of lists:

s = [['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring'], ['second\tbar\tfoo', 'third\tpractice\tbar']]

new_s = [[re.split("\\t", b) for b in i] for i in s]

new_s now stores:

[[['t__f326ea56'], ['foo', 'bar', 'quax'], ['some', 's', 'string']], [['second', 'bar', 'foo'], ['third', 'practice', 'bar']]]

To transpose the data in new_s :

new_s = [[b for b in i if len(b) > 1] for i in new_s]

final_s = list(map(lambda x: zip(*x), new_s))

final_s will now store the data in the original way you want it:

[[('foo', 'some'), ('bar', 's'), ('quax', 'string')], [('second', 'third'), ('bar', 'practice'), ('foo', 'bar')]]

Using "straight" str.split() function:

l = ['t__f326ea56', 'foo\tbar\tquax', 'some\ts\tstring']
items1, items2 = l[1].split('\t'), l[2].split('\t')
s1, s2, s3, s4 = l[0], [items1[0], items2[0]], [items1[1], items2[1]], [items1[2], items2[2]]
print(s1, s2, s3, s4)

The output:

t__f326ea56 ['foo', 'some'] ['bar', 's'] ['quax', 'string']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM