Search code examples
pythonpython-re

Python Re- match exact string with pattern


string1="block12emp"

string2="block12"

reg=re.match('^[\D]{2,6}[\d]{2}\D{3}$', string1) # returns, block12emp

The above regex works correctly

reg=re.match('^[\D]{2,6}[\d]{2}\D{3}$', string2) # returns, block12

Here, the excepted output for string2 is Null, but the regex returns block12

This regex will not match the full pattern, and returns only what matches in the string

How to match the string excatly with this pattern

Thanks


Solution

  • so i have checked on your pattern and it seems to be valid and working so i tried to check it myself on python shell and it stills works

    >>> import re
    >>>
    >>>
    >>> string1 = "block12emp"
    >>>
    >>> string2 = "block12"
    >>>
    >>>
    >>> reg_pattern = '^[\D]{2,6}[\d]{2}\D{3}$'
    >>>
    >>> res1 = re.match(reg_pattern, string1)
    >>> res2 = re.match(reg_pattern, string2)
    >>>
    >>>
    >>> res1.group()
    'block12emp'
    >>> res2.group()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'group'
    

    and this works as expected so when re.match find a string matching the pattern it returns it else it returns None

    re-check how your logic deals with the exception and what exactly you return