简体   繁体   中英

Remove brackets from strings with regex in Python

Currently, I have two string with bracket

'NI,DG,BJ (1).jpg' , 'N1,DG,BJ(1).jpg'

For each string, I want to split and obtain each character split by the comma, except for the enclosing bracket.

This is achieable via the following

import re
s=['NO,AG,GK.jpg','NI,DG,BJ (1).jpg','N1,DG,BJ(1).jpg']

all_v=[]
for d in s:
  k=re.sub("(\s\(\d+\))?(\.jpg)?", "", d).split(',')

  if '(' in k[-1] :
    k[-1]=k[-1].split('(')[0]

  all_v.append(k)

But, since the bracket can be close or separated by space, I have to add if statement.

I wonder whether there is regex smart way to skip the if-else statement

Expected output

['NO', 'AG', 'GK']
 ['NI', 'DG', 'BJ']
 ['N1', 'DG', 'BJ']
import re
s=['NO,AG,GK.jpg','NI,DG,BJ (1).jpg','N1,DG,BJ(1).jpg']

for i in s:
    [re.search('(\w+).*',k).group(1) for k in i.split(',')]

rsults

['NO', 'AG', 'GK']
['NI', 'DG', 'BJ']
['N1', 'DG', 'BJ']

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