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

时间:2016-07-20 07:29:18

标签: python regex

我想知道从长字符串中提取括号中的最后一个字符串的方法。所以我需要一个函数extract_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])

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

5 个答案:

答案 0 :(得分:3)

您可以使用正则表达式:

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

你可以搜索所有括号:

l = re.findall('\((.*?)\)', s) # Search for all brackets (and store their content)
#['hello', 'name', 'Luis']
theOne = l[-1] # Get the last one
#'Luis'

答案 1 :(得分:3)

import re

def extract_last(val):
    r = re.findall(r'\((\w+)\)', val)
    return r[-1] if r else None

答案 2 :(得分:2)

使用splitrsplit是实现目标的一种方式

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

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

答案 3 :(得分:1)

你真的不需要在这里使用正则表达式。只需使用rpartition在最后一次出现(时将字符串拆分,然后从切片结果中将) >>> string = '(hello) my (name) is (Luis)' >>> string.rpartition('(')[-1].strip(')') 'Luis' 拆分。

Phaser.States

答案 4 :(得分:-1)

你可以使用split函数来获取子字符串, 你可以试试这个:

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

extract_last('(hello) my (name) is (Luis)')

现在temp包含由&#34;分隔的所有单词&#34;(空格) 从最后读取并获得您的价值

相关问题