如何在Python中匹配空格和字母数字字符

20

我正在尝试匹配一个带有空格和字母数字字符的字符串,如下所示:

test = django cms

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

patter = '\s'

很遗憾,这只能匹配空格,所以当在 re 对象中使用搜索方法找到匹配时,它只返回空白部分,而不是整个字符串。我该如何更改模式,以使其找到匹配时返回整个字符串?


你认为什么是“字母数字字符”?如果包括字母、数字和下划线,那么你会发现 \w 很方便。 - jpsimons
2个回答

44
import re

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

返回

('this matches',)

(1) 冗余的括号 (2) OP 正在使用 search() 而不是 match() - John Machin
4
(1)在我看来,括号强调整个匹配组被返回;(2)使用 re.search() 同样有效。 - Hugh Bothwell
1
如果短语中恰好有一个空格,则上述正则表达式将起作用,但我建议将其更改为匹配任意数量的以空格分隔的单词:match = re.match("([\w|\s]+)", test) - Jake Anderson

2
如果有多个空格,请使用以下正则表达式:
'([\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',)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接