Quba
Quba

Reputation: 5306

python regex match not working

It might be a silly question but i can not get it working.

import re
def name_validator(value):
    reg = re.compile(r'^\D*&')
    if not reg.match(value):
        raise ValueError

I want to match any string that do not contains digits. But it always raise ValueError.

>>> import re
def name_validator(value):
    reg = re.compile(r'^\D*&')
    if not reg.match(value):
        raise ValueError
>>> name_validator('test')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in name_validator
ValueError

Upvotes: 1

Views: 911

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

I want to match any string that does not contains digits.

The \D matches a non-digit symbol. A ^\D*$ matches an empty string and any string without digits inside.

You need to use

reg = re.compile(r'\D*$') # Note  DOLLAR symbol at the end
if not reg.match(value):

Or

reg = re.compile(r'^\D*$') # Note the CARET symbol at the start and the DOLLAR symbol at the end
if not reg.search(value):

Upvotes: 2

Related Questions