Python中的正则表达式,用于检查字符串是否只包含字母、数字和点号(.)。

6

我正在尝试开发一个正则表达式来匹配只包含字母、数字、空格和点(.)的字符串,而且这些字符可以随意排列。

例如:

hello223 3423.  ---> True
lalala.32 --->True
.hellohow1 ---> True
0you and me = ---> False (it contains =)
@newye ---> False (it contains @)
With, the name of the s0ng .---> False (it start with ,)

我正在尝试使用这个,但它总是返回匹配结果:
m = re.match(r'[a-zA-Z0-9,. ]+', word)

有什么想法吗?

另外一个表述问题的方式是,除了字母、数字、点和空格之外,还有没有其他不同的字符?

提前致谢。


全部还是任意?例如,“A”会匹配吗? - Alex K.
@AlexK。另一种表达问题的方式是,除了字母、数字、点和空格之外,还有任何不同的字符吗? - Joan Triay
2个回答

5
您需要添加$
re.match(r'[a-zA-Z0-9,. ]+$', word)

谢谢,看起来它正在工作,$?是什么意思? - Joan Triay
1
@JoanTriay 它匹配字符串的结尾。如果没有它,匹配可以在中间发生。请参见此处$ - llllllllll

2

re.search() 解决方案:

import re

def contains(s):
    return not re.search(r'[^a-zA-Z0-9. ]', s)

print(contains('hello223 3423.'))    # True
print(contains('0you and me = '))    # False
print(contains('.hellohow1'))        # True

考虑到StackOverflow上的这个re.match vs. re.search线程,我更喜欢使用re.search;它的匹配对象还包含了不匹配的位置和内容,这对于错误报告可能会有用。 - sshine

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