简体   繁体   English

使用 Python 中的正则表达式从字符串中删除括号

[英]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' '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.但是,由于括号可以关闭或用空格分隔,我必须添加if语句。

I wonder whether there is regex smart way to skip the if-else statement我想知道是否有正则表达式聪明的方法来跳过 if-else 语句

Expected output预期 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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