Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从字符串中提取括号之间的最后一个字符串-python_Python_Regex - Fatal编程技术网

从字符串中提取括号之间的最后一个字符串-python

从字符串中提取括号之间的最后一个字符串-python,python,regex,Python,Regex,我想知道如何从长字符串中提取括号之间的最后一个字符串。所以我需要一个函数,extract\u last,例如,它可以让我得到这样的输出: >> extract_last('(hello) my (name) is (Luis)') >> 'Luis' 我如何在不使用for的情况下实现这一点,我正在寻找最聪明的方法 我所采用的实施方式非常有效。我没有用所有的可能性来测试它,但最简单的事情可以很好地完成: def extract_last(string): brac

我想知道如何从长字符串中提取括号之间的最后一个字符串。所以我需要一个函数,
extract\u last
,例如,它可以让我得到这样的输出:

>> extract_last('(hello) my (name) is (Luis)')
>> 'Luis'
我如何在不使用for的情况下实现这一点,我正在寻找最聪明的方法

我所采用的实施方式非常有效。我没有用所有的可能性来测试它,但最简单的事情可以很好地完成:

def extract_last(string):
    bracket_found = False
    characters = []
    for character in string[::-1]:
        if character == ')':
            bracket_found = True
            continue
        if(character == '(' and bracket_found):
            break;
       if(bracket_found and character != ')'):
            characters.append(character)
    return ''.join(characters[::-1])

但是这个解决方案有很多行,我知道使用正则表达式或类似的东西,我可以用一行或两行的解决方案来完成

您可以使用正则表达式:

s = '(hello) my (name) is (Luis)'
re.sub('^.*\((.*?)\)[^\(]*$', '\g<1>', s) # Search for the content between the last set of brackets
# 'Luis'

使用
split
rsplit
将是一种方法

>>> a= '(hello) my (name) is (Luis)'
>>> a.split('(')[-1].split(')')[0]
'Luis'
>>> a.rsplit('(')[-1].rsplit(')')[0]
'Luis'
>>> 

其中[-1]是找到的最后一项,[0]是第一项

您可以使用拆分函数获取子字符串,
import re

def extract_last(val):
    r = re.findall(r'\((\w+)\)', val)
    return r[-1] if r else None
您可以尝试以下方法:

def extract_last(my_string):
    temp = my_string.split(" ")
    print temp[-1]   ## get last element

extract_last('(hello) my (name) is (Luis)')
现在temp包含所有以“”分隔的单词(空格)
只需阅读上一篇文章并获取您的值

您真的不需要在这里使用正则表达式。只需在最后一次出现
然后是
时从切片结果中拆分字符串

>>> string = '(hello) my (name) is (Luis)'
>>> string.rpartition('(')[-1].strip(')')
'Luis'

为什么?为什么不为使用
?您尝试过什么?您的正则表达式可以从贪婪的
*
开始。您的正则表达式可以在参数中查找单词,并捕获它们(使用参数):
regex=re.compile(r'\(.*))
。如果运行
regex.findall()
,将得到一个包含所有匹配项的数组。然后使用括号访问最后一个单词(
[-1]
),请查看OP的结果,该结果与您的结果不同。可能是最后一个单词不是最后一个封闭的单词。e、 我的名字叫路易斯。这里OP想要得到
'name'
。我选择了你的答案,因为它在括号之间的字符串中有帐户空格。谢谢
>>> string = '(hello) my (name) is (Luis)'
>>> string.rpartition('(')[-1].strip(')')
'Luis'