简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM