DEV Community

Aditya Varma
Aditya Varma

Posted on

Regex solution

Problem Description:

Regex needs to accepts all strings of type abc.xyz.mno, it should be composed of multiple strings all joined by '.'. The joined strings can only contain [a-z][0-9], even capital characters are not allowed.

Valid cases

abc.bcd.edsaf.asdfds
abc.asdf123.1234adf
abc.ad

Invalid cases

abc
abc.
abc.132A
ASD
1234
1234ASF.

The solution that I came up with is this

^[a-z0-9]+\.[a-z0-9]([a-z0-9]*|\.[a-z0-9])+$

I am not sure whether this is the most efficient solution possible?

Top comments (4)

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

Hey thanks for sharing this!

Collapse
 
justinenz profile image
Justin • Edited

I'm not greatly familiar with regex so I can't speak to efficiency, but this is what I came up with on regexr.com and pythex.org/ (both require multiline to be selected for start/end ^ $ to work)

Note: strangely, your solution didn't have any matches on pythex, but we have the same results on regexr; also, I added an invalid case for a string starting with a '.'

Expression
^([a-z\d]+(\.([a-z\d]+))+)$

Text
Valid cases

abc.bcd.edsaf.asdfds
abc.asdf123.1234adf
abc.ad

Invalid cases
.abc.ab
abc
abc.
abc.132A
ASD
1234
1234ASF.
Collapse
 
adityavarma1234 profile image
Aditya Varma

I have used regex101.com/ for figuring it out. It worked for me there a while back and it is not working again! I am not really sure why! Need to learn more about regex I guess.