【问题标题】:Regular expression in python that check if the string just contains letters, numbers and dot(.)python中的正则表达式,用于检查字符串是否只包含字母、数字和点(。)
【发布时间】:2018-08-20 15:19:06
【问题描述】:

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

像这样:

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”会匹配吗?
  • @AlexK。提出问题的其他方式是字母、数字、点和空格是否有任何不同的字符?

标签: python regex python-2.7


【解决方案1】:

您需要添加$:

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

【讨论】:

  • 谢谢,它似乎有效,$ 是什么意思?
  • @JoanTriay 它匹配字符串的结尾。没有它,比赛可以在中间。见$here
【解决方案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 上的 this re.match vs. re.search 线程,我更喜欢 re.search;它的匹配对象还包含可能对错误报告有用的不匹配的位置和内容。
猜你喜欢
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
相关资源
最近更新 更多