Python3像这样负面看待

时间:2017-07-26 09:22:40

标签: python python-3.x

我想找到一个像@@壁橱一样的字符串,如下所示

def get_closet(ss):
    m = re.search('(?<=@@)(.*)$', ss, re.I)
    if m:
        print('find')
        print(m.groups())
    else:
        print('not find')



str1 = '@@ AF @@ BV @@ CX @@ DDFFF'  # should return `DDFFF`
str2 = ' DDFFF'  # should return `DDFFF` 
for x in str1, str2:
    get_closet(x)

我找到m = re.search('((?!@@).)*$', ss, re.I|re.S)但输入为str1时,会返回@ DDFFF而不是DDFFF

1 个答案:

答案 0 :(得分:1)

您可以使用import functools import itertools import numpy import operator import perfplot def forfor(a): return [item for sublist in a for item in sublist] def sum_brackets(a): return sum(a, []) def functools_reduce(a): return functools.reduce(operator.concat, a) def functools_reduce_iconcat(a): return functools.reduce(operator.iconcat, a, []) def itertools_chain(a): return list(itertools.chain.from_iterable(a)) def numpy_flat(a): return list(numpy.array(a).flat) def numpy_concatenate(a): return list(numpy.concatenate(a)) perfplot.show( setup=lambda n: [list(range(10))] * n, kernels=[ forfor, sum_brackets, functools_reduce, functools_reduce_iconcat, itertools_chain, numpy_flat, numpy_concatenate ], n_range=[2**k for k in range(16)], logx=True, logy=True, xlabel='num lists' )

(?:@@| )?([^@@ ]+)$

但是,你不一定需要正则表达式:

import re

print(re.findall('(?:@@| )?([^@@ ]+)$', '@@ AF @@ BV @@ CX @@ DDFFF'))
# ['DDFFF']
print(re.findall('(?:@@| )?([^@@ ]+)$', ' DDFFF'))
# ['DDFFF']

甚至更通用:

def foo(string):
    try:
        return string[string.rindex('@@'):].strip('@@ ')
    except ValueError:  # if no @@
        return string.strip()

string = '@@ AF @@ BV @@ CX @@ DDFFF'
print(foo(string))
# 'DDFFF'
string = ' DDFFF'
print(foo(string))
# 'DDFFF'