【问题标题】:how to match whitespace and alphanumeric characters in python如何在python中匹配空格和字母数字字符
【发布时间】:2011-02-19 00:49:01
【问题描述】:

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

test = django cms

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

patter = '\s'

不幸的是,它只匹配空格,所以当使用 re 对象中的搜索方法找到匹配时,它只返回空格,而不是整个字符串,我该如何更改模式以便它返回整个字符串时找到匹配项?

【问题讨论】:

  • 您认为“字母数字字符”是什么?如果是字母、数字和下划线,你会发现 \w 很方便。

标签: python regex pattern-matching


【解决方案1】:
import re

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

返回

('this matches',)

【讨论】:

  • (1) 多余的括号 (2) OP 使用的是search() 而不是match()
  • @John Machin:(1)我认为括号强调返回整个组; (2) 它同样适用于 re.search()。
  • 如果短语中只有一个空格,上述正则表达式将起作用,但我建议将其更改为此以匹配任意数量的空格分隔单词:match = re.match("([\w|\s]+)", test)
【解决方案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',)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多