6

I am trying to develop a regular expression for match if a string just contains letters, numbers, space and dot(.) anywhere and with no order.

Like this:

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

I am trying with this one but is always returning match:

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

Any idea?

Other way to formulate the question is are there any character diferent of letters, numbers, dot and space?

Thanks in advance

Joan Triay
  • 1,518
  • 6
  • 20
  • 35

2 Answers2

5

You need to add $:

re.match(r'[a-zA-Z0-9,. ]+$', word)
llllllllll
  • 16,169
  • 4
  • 31
  • 54
2

re.search() solution:

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Considering [this `re.match` vs. `re.search`](https://stackoverflow.com/a/180993/235908) thread on StackOverflow, I'd prefer `re.search`; its match object also contains the position and content of the mismatch which might be useful for error reporting. – sshine Mar 12 '18 at 15:02