我想知道从长字符串中提取括号之间最后一个字符串的方法。所以我需要一个函数,extract_last例如,让我得到这样的输出:
>> extract_last('(hello) my (name) is (Luis)')
>> 'Luis'
Run Code Online (Sandbox Code Playgroud)
我如何在不使用 for 的情况下实现这一点,我正在寻找最聪明的方法。
我实施的 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])
Run Code Online (Sandbox Code Playgroud)
但是这个解决方案有很多行,我知道使用正则表达式或类似的东西,我可以用一两行的解决方案来完成。
您可以使用正则表达式:
s = '(hello) my (name) is (Luis)'
re.sub('^.*\((.*?)\)[^\(]*$', '\g<1>', s) # Search for the content between the last set of brackets
# 'Luis'
Run Code Online (Sandbox Code Playgroud)
你可以对所有括号进行搜索:
l = re.findall('\((.*?)\)', s) # Search for all brackets (and store their content)
#['hello', 'name', 'Luis']
theOne = l[-1] # Get the last one
#'Luis'
Run Code Online (Sandbox Code Playgroud)