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

20 投票
2 回答
69398 浏览
提问于 2025-04-16 12:06

我正在尝试匹配一个中间有空格的字符串,并且这个字符串里有字母和数字,像这样:

test = django cms

我试过用以下的模式来匹配:

patter = '\s'

但不幸的是,这个模式只匹配空格,所以当我用正则表达式的搜索方法找到匹配时,它只返回空格,而不是整个字符串。我该如何修改这个模式,以便在找到匹配时返回整个字符串呢?

2 个回答

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',)
44
import re

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

返回值

撰写回答