删除字符串前后空格的Python正则表达式

2024-06-06 17:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个很小的python程序中构建,但找不到正确的regex。我来解释一下:

我有下一根弦

bar = '    Type of network         : Infrastructure'

代码如下:

foo = re.findall(r'(\w+(\s\w+)+)\s+:\s+(\w+)', bar)
print(foo)

我获得:

[('Type of network', ' network', 'Infrastructure')]

我想:

[('Type of network', 'Infrastructure')]

我知道我可以用“:”来拆分字符串,并修剪空格,但我更喜欢正则表达式。你知道吗

多谢了


Tags: of字符串代码程序refootypebar
3条回答

只是另一个不使用regex的解决方案[ x.strip() for x in bar.split(':')]

输出:['Type of network', 'Infrastructure']

下一个怎么样?你知道吗

foo = re.findall(r'\s*(.*?)(?:\s*:\s*)(.+)(?<!\s)', bar)

它还处理以下字符串:

'    Type of network         : Infra structure  '

也许您想使用非捕获括号:

(\w+(?:\s\w+)+)\s+:\s+(\w+)

相关问题 更多 >