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

2024-10-04 03:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试开发一个正则表达式来匹配如果一个字符串只包含字母、数字、空格和点(.),并且没有顺序。在

像这样:

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 ,)

我正在尝试这个,但总是返回匹配:

^{pr2}$

有什么想法吗?在

另一种表达问题的方法是,字母、数字、点和空格是否有区别?在

提前谢谢


Tags: andthe字符串falsetrue顺序字母it
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

您需要添加$

re.match(r'[a-zA-Z0-9,. ]+$', word)

相关问题 更多 >