Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.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中匹配空格和字母数字字符 我试图匹配一个中间有空格的字符串和像SO:的字母数字字符。 test = django cms_Python_Regex_Pattern Matching - Fatal编程技术网

如何在python中匹配空格和字母数字字符 我试图匹配一个中间有空格的字符串和像SO:的字母数字字符。 test = django cms

如何在python中匹配空格和字母数字字符 我试图匹配一个中间有空格的字符串和像SO:的字母数字字符。 test = django cms,python,regex,pattern-matching,Python,Regex,Pattern Matching,我已尝试使用以下模式进行匹配: patter = '\s' 不幸的是,它只匹配空白,因此当使用re对象中的搜索方法找到匹配时,它只返回空白,而不是整个字符串,如何更改模式,以便在查找匹配时返回整个字符串 import re test = "this matches" match = re.match('(\w+\s\w+)', test) print match.groups() 返回 ('this matches',) 如果有多个空间,请使用以下regexp: '([\w\s]+)'

我已尝试使用以下模式进行匹配:

patter = '\s'
不幸的是,它只匹配空白,因此当使用re对象中的搜索方法找到匹配时,它只返回空白,而不是整个字符串,如何更改模式,以便在查找匹配时返回整个字符串

import re

test = "this matches"
match = re.match('(\w+\s\w+)', test)
print match.groups()
返回

('this matches',)

如果有多个空间,请使用以下regexp:

'([\w\s]+)'
范例

In [3]: import re

In [4]: test = "this matches and this"
   ...: match = re.match('([\w\s]+)', test)
   ...: print match.groups()
   ...: 
('this matches and this',)

你认为“字母数字字符”是什么?如果字母、数字和下划线,你会发现很方便。(1)冗余括号(2)OP使用<代码>搜索()/<代码>不<代码> Matd()/代码> @ John Machin:(1)在我的思维方式中,括号强调整个组被返回;(2) 它同样适用于re.search()。如果短语中只有一个空格,上面的正则表达式也可以使用,但我建议将其改为此以匹配任意数量的空格分隔的单词:
match=re.match([\w\s]+),test)