我需要帮助从一个字符串中提取多个子字符串并将其分配给一个列表,并且那些所需的子字符串具有相似的开始子字符串和结束子字符串,
例如,如果我有这样一个字符串:“开始某事某事结束开始什么都没有结束”
如何提取“something something”和“nothing nothing”并将其附加到列表中。
最佳答案
您可以使用 re.findall
.
>>> text = 'start something something end start nothing nothing end'
>>> re.findall('start (.+?) end', text)
['something something', 'nothing nothing']
Return all non-overlapping matches of pattern in string, as a list of strings.
图案是
开始
后跟一个空格(
表示我们感兴趣的部分(组)的开始.
表示任意字符+?
表示至少有一个,但越少越好)
表示我们感兴趣的部分(组)结束- 一个空格后跟
end
。
The string is scanned left-to-right, and matches are returned in the order found.
If one or more groups are present in the pattern, return a list of groups;
我们正在使用组,如上所示
this will be a list of tuples if the pattern has more than one group.
我们只使用一组。
Empty matches are included in the result.
关于python - 如何从 python 中的字符串中提取多子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672956/