简体   繁体   English

使用正则表达式删除python中括号中的内容

[英]Use regular expression to remove contents in brackets in python

I have a list : 我有一个list

['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']

also as as string '14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\\n' 也作为字符串'14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\\n'

Using regex, how do I return: 使用正则表达式,如何返回:

['14147618', '6137776, '5943229', 2066613']

You don't need RegEx at all, you can simply filter out the data which has only digits in them, with this list comprehension 您根本不需要RegEx,只需使用此列表理解功能,就可以过滤出仅包含数字的数据

print [item for item in data if item.isdigit()]
# ['14147618', '6137776', '5943229', '2066613']

Or you can also use filter builtin function, like this 或者您也可以使用filter内置函数,例如

print filter(str.isdigit, data)
# ['14147618', '6137776', '5943229', '2066613']

Edit: If you have the entire data as a single string, you can split the data based on whitespace characters and then use the same logic 编辑:如果您将整个数据作为单个字符串,则可以根据空格字符拆分数据,然后使用相同的逻辑

data = '14147618 (100%)   6137776 (43%)   5943229 (42%)   2066613 (14%)  TOTAL\n'
print [item for item in data.split() if item.isdigit()]
# ['14147618', '6137776', '5943229', '2066613']
print filter(str.isdigit, data.split())
# ['14147618', '6137776', '5943229', '2066613']

As @thefourtheye said, it's not necessary to use regex at all, but if you really want to do it with regex, you can use: 正如@thefourtheye所说,根本不需要使用正则表达式,但是如果您真的想使用正则表达式,则可以使用:

import re

a = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
result = []

for e in a:
    m = re.match(r'\d+', e)
    if m is not None:
        result.append(e)

print result
# ['14147618', '6137776', '5943229', '2066613']

Note: This can also be written as list comprehension: 注意:这也可以写成列表理解:

print [e for e in a if re.match(r'\d+', e)]

Here is one way: 这是一种方法:

>>> l = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
>>> [el for el in l if re.match(r'\d+$', el)]
['14147618', '6137776', '5943229', '2066613']

Use re module: 使用re模块:

>>> import re
>>> [item for item in s if re.match(r'\d+',item)]
['14147618', '6137776', '5943229', '2066613']

No need to use re module at all , you can use filter over list . 完全不需要使用re模块,可以在list使用filter

Try this , 尝试这个 ,

>>> a=['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
>>> filter(str.isdigit, a)
['14147618', '6137776', '5943229', '2066613']
>>>

或者,如果要除最后一个元素外的偶数索引元素:

print [data[i] for i in range(0,len(data)-1,2)]

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

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