我对Python和regex非常陌生。我快到了,但6个小时后没能解决这个问题。希望有人能帮忙。
我的字符串如下:
str_1 = & peers & & apples & & lemon juice & & Strawberries & & Mellon & 我想要一个新的列表,其中包含:['peers','apples','lemon juice','Strawberries','Mellon']。因此,没有所有的空白和&符号。
我的代码如下:
list_1 = re.compile(r'(?<=&)(.*?)(?=&)').findall(str_1)然而,我得到了这样的东西:
list_1 = [' peers ', ' ', ' apples ', ' ', ' lemon juice ', ' ', ' Strawberries ', ' ', ' Mellon']有人能帮我弄到:
['peers','apples','lemon juice','Strawberries','Mellon']发布于 2022-10-03 09:33:53
你不需要雷克斯来做这个
>>> str_1 = '& peers & & apples & & lemon juice & & Strawberries & & Mellon &'
>>> ls = [x.strip() for x in str_1.split('&')]
>>> ls = [x for x in ls if x]
>>> ls
['peers', 'apples', 'lemon juice', 'Strawberries', 'Mellon']如果你还想要一个正则表达式,那么
>>> re.findall(r'[^& ][^&]*[^& ]', str_1)
['peers', 'apples', 'lemon juice', 'Strawberries', 'Mellon']发布于 2022-10-03 09:31:48
如果您必须使用regex,可以使用
re.findall(r'[^&\s]+(?:[^&]*[^&\s])?', str_1)见regex演示。详细信息
[^&\s]+ - &和空格以外的一个或多个字符- -(?:[^&]*[^&\s])? --除&之外的任何字符的可选序列,然后是除&或空格之外的字符。import re
str_1 = "& peers & & apples & & lemon juice & & Strawberries & & Mellon & "
print( re.findall(r'[^&\s]+(?:[^&]*[^&\s])?', str_1) )
# => ['peers', 'apples', 'lemon juice', 'Strawberries', 'Mellon']非正则表达式解决方案看起来像
[x.strip() for x in str_1.split('&') if x.strip()]见这个Python演示。在这里,您使用&字符拆分一个字符串,并且只保留不为空的项或所有空白,并去掉前导/尾随空格。
https://stackoverflow.com/questions/73933511
复制相似问题