Python正则表达式-从字符串末尾获取一块空白

Python正则表达式-从字符串末尾获取一块空白,python,regex,Python,Regex,我正在尝试编写一个正则表达式,它从字符串的任意一侧获取空白块。我可以开始,但我似乎抓不到最后一块 s = ' This is a string with whitespace on either side ' strip_regex = re.compile(r'(\s+)(.*)(something to grab end block)') mo = strip_regex.findall(s) 我得到的输出是: [(' ', 'This is a strin

我正在尝试编写一个正则表达式,它从字符串的任意一侧获取空白块。我可以开始,但我似乎抓不到最后一块

s = '     This is a string with whitespace on either side     '

strip_regex = re.compile(r'(\s+)(.*)(something to grab end block)')
mo = strip_regex.findall(s)
我得到的输出是:

[('        ', 'This is a string with whitespace on either side        ')]
我在结尾的时候一直在考虑这个问题,我能得到的最好的结果就是一个空格,但我永远都不能在“side”结尾之前抓住字符串。我不想使用side中的字符,因为我希望正则表达式能够处理任何被空格包围的字符串。我很确定这是因为我使用的是(*),它只是在第一个空格块之后获取所有内容。但是,我不知道如何使它在结束空格块之前停止


谢谢您的帮助:)

如果您想删除空白,可以使用strip()。 见:

至于你的正则表达式,如果你想要开始和结束的空格,我建议匹配整行,中间部分不要像这样贪婪:

s = '     This is a string with whitespace on either side     '
strip_regex = re.compile(r'^(\s+)(.*?)(\s+)$')
mo = strip_regex.findall(s)
结果:

[('     ', 'This is a string with whitespace on either side', '     ')]

关于贪婪的更多信息:

太棒了,谢谢!从字面上说,只要将美元移出最后一组,它就会起作用!我试图编写一个正则表达式来模拟strip()函数:)