如何在Python中使用Regex匹配空间

时间:2015-03-23 16:01:22

标签: python regex

为什么下面的代码与空格字符不匹配?

import re

hasSpace = re.compile(' ')

string = 'hello world'

if(hasSpace.match(string)):
    print("Found a space")
else:
    print("No space")

我也尝试过使用:

hasSpace = re.compile('\s')

但它也不匹配。我还尝试添加 r 来使字符串生成,但结果相同。

有什么线索?

3 个答案:

答案 0 :(得分:1)

您可能想要使用search方法。 search "scans through a string, looking for any location where this RE matches."

import re

hasSpace = re.compile(' ')

string = 'hello world'

if(hasSpace.search(string)):
    print("Found a space") # gets printed
else:
    print("No space")

string = 'helloworld'

if(hasSpace.search(string)):
    print("Found a space")
else:
    print("No space") # gets printed

您尝试使用的是match"determines if the RE matches at the beginning of the string."

答案 1 :(得分:1)

通过搜索替换match

>>> if(hasSpace.search(string)):
...      print("Found a space")
... else:
...     print("No space")
...
Found a space

答案 2 :(得分:0)

如果你真的想用匹配得到答案那么你可以这样做(不推荐。) 因为匹配从头开始,你需要将'hello'这个单词的5个字母与'.....'匹配,然后匹配空格

import re
hasSpace = re.compile('..... ')
string = 'hello world'
if(hasSpace.match(string)):
  print("Found a space")
else:
  print("No space")

<强>输出

Found a space