DEV Community

loading...

Discussion on: Regex solution

Collapse
learnbyexample profile image
Sundeep • Edited

With re module, fullmatch is used to match only whole string

>>> expr = re.compile(r'[a-z\d]+(?:\.[a-z\d]+)+')
>>> strings = ['abc.bcd.edsaf.asdfds', 'abc.asdf123.1234adf', 'abc.ad',
...            'abc', 'abc.', 'abc.132A', 'ASD', '1234', '1234ASF.']
>>> [bool(expr.fullmatch(s)) for s in strings]
[True, True, True, False, False, False, False, False, False]

With regex module, you can use subexpression call to avoid duplication. Also, possessive quantifiers can be used here to speed up things.

>>> expr = regex.compile(r'([a-z\d]++)(?:\.(?1))++')
>>> [bool(expr.fullmatch(s)) for s in strings]
[True, True, True, False, False, False, False, False, False]
Collapse
adityavarma1234 profile image
Aditya Varma Author

Hey thanks for sharing this!