Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单python正则表达式无法按预期工作_Python_Regex - Fatal编程技术网

简单python正则表达式无法按预期工作

简单python正则表达式无法按预期工作,python,regex,Python,Regex,我试图提取出-前面的数字和后面的字符串的其余部分,但无法同时提取这两个数字。以下是交互式终端的输出: a='#232-你好 >>>关于findall(“#(.*)-(.*)”,a) [('232', '')] 为什么我的正则表达式不能正常工作?*?是非贪婪的,即它将匹配最小的子字符串,您需要贪婪版本,即后一个的*(匹配最长的子字符串): In [1143]: a = '#232 - Hello There'

我试图提取出
-
前面的数字和后面的字符串的其余部分,但无法同时提取这两个数字。以下是交互式终端的输出:

a='#232-你好 >>>关于findall(“#(.*)-(.*)”,a) [('232', '')] 为什么我的正则表达式不能正常工作?

*?
是非贪婪的,即它将匹配最小的子字符串,您需要贪婪版本,即后一个的
*
(匹配最长的子字符串):

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')

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

([0-9]+)\s*-\s*(.*)
试验 输出
您的正则表达式很好,只是使用了
re
中的错误函数。以下内容与内容正确匹配:

m = re.fullmatch('#(.*?) - (.*?)', a)
你需要一个正则表达式吗<代码>拆分和
剥离
就可以了。“可能吧”?正则表达式是非常确定的
[('232', 'Hello There')]
m = re.fullmatch('#(.*?) - (.*?)', a)