1

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

2
  • You last piece of code outputs nothing in my hands, not "block12". Commented Dec 25, 2021 at 12:28
  • It gives the correct result.. for string1, block12emp, for string2 nonetype my re version: 2.2.1 and python: 3.7 Commented Dec 25, 2021 at 12:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.