Py学习  »  Python

简单的python正则表达式不能按预期工作

smaili • 4 年前 • 701 次点击  

我想在 - 剩下的字符串在后面,但它不能同时提取出来。下面是交互终端的输出:

>>> a = '#232 - Hello There'
>>> re.findall('#(.*?) - (.*?)', a)
[('232', '')]

为什么我的正则表达式不能正常工作?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47068
 
701 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Eric
Reply   •   1 楼
Eric    4 年前

你的正则表达式很好,你只是使用了错误的函数 re 是的。以下内容匹配正确:

m = re.fullmatch('#(.*?) - (.*?)', a)
Emma
Reply   •   2 楼
Emma    4 年前

此表达式可能会提取这些所需的值:

([0-9]+)\s*-\s*(.*)

Demo

测试

import re

print(re.findall("([0-9]+)\s*-\s*(.*)", "#232 - Hello There"))

输出

[('232', 'Hello There')]
heemayl
Reply   •   3 楼
heemayl    4 年前

.*? 非贪婪 也就是说,它将匹配最小的子字符串,您需要 贪婪的 版本,即 .* (匹配最长的子字符串)对于后者:

In [1143]: a = '#232 - Hello There'                                                                                                                                                                         

In [1144]: re.findall('#(.*?) - (.*?)', a)                                                                                                                                                                  
Out[1144]: [('232', '')]

In [1145]: re.findall('#(.*?) - (.*)', a)                                                                                                                                                                   
Out[1145]: [('232', 'Hello There')]

但你应该用 str 处理此类简单案例的方法,例如使用 str.split 打开拆分 - 以下内容:

In [1146]: a.split(' - ')                                                                                                                                                                      
Out[1146]: ['#232', 'Hello There']

str.partition - 切片:

In [1147]: a.partition(' - ')[::2]                                                                                                                                                                          
Out[1147]: ('#232', 'Hello There')