我有一个字符串,如下所示:
" I wanted my friends (he), (she), (they) around"
我想得到一个包含["he", "she", "they"]
的列表。
copy = " (he), (she), (they)"
x = re.findall(r'^{.}$', copy)
但是这给了我一个空列表作为输出。
我还尝试了以下操作:
import re
copy = '{he},{she}, {they}'
x = re.findall(r'{([^]]*)}', copy)
print(x)
但是在这个例子中,输出是:
['he},{she}, {they']
您可以使用((w+))
(任何由圆括号包围的单词字符的连续):
import re
re.findall('((w+))', your_string)
输入:your_string = " I wanted my friends (he), (she), (they) around"
输出:['he', 'she', 'they']
首先,您在示例中有圆括号(
)
,而不是花括号{
}
,其次^
表示行或字符串的开始(取决于模式),而您的括号表达式在里面,第三$
表示行或字符串的结束(取决于模式),而您的括号表达式在里面。你应该做
import re
text = " I wanted my friends (he), (she), (they) around"
print(re.findall(r'((.+?))',text))
输出['he', 'she', 'they']
请注意,我使用所谓的原始字符串来避免过度转义的需要(参见re
模块文档以获得进一步的讨论),并且需要使用(
和)
来表示文字(和文字),否则(和)表示组,这也用于上述模式。.+?
表示非贪婪匹配一个或多个任意字符,?
是重要的,以避免单一匹配he), (she), (they
。