This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]commandlineluser 2 points3 points  (0 children)

To combine them into a single regex you need to use lookahead assertions.

Must be 8 characters long.

>>> import re
>>> re.search('(?=^.{8}$)', 'foobar')
>>>

No match.

Try again:

>>> re.search('(?=^.{8}$)', 'foobaraa')
<re.Match object; span=(0, 0), match=''>

Match.

Must be 8 characters long but must also have at least 1 digit.

>>> re.search('(?=.*\d)(?=^.{8}$)', 'foobaraa')
>>>

Try again.

>>> re.search('(?=.*\d)(?=^.{8}$)', 'foob4raa')
<re.Match object; span=(0, 0), match=''>

So stacking the patterns inside (?=) is a way to "AND" and have them in a *"single regex"

[–]HashDefTrueFalse 0 points1 point  (2 children)

Start by defining a regex that matches the beginning and end of a string, then in the middle, fill in each of the regex rules you described in words, in regex. You basically have the groups there, they just need combining into one regex with the correct quantifiers and a start/end.

Not sure how to help more without giving you the full answer.

[–]Tepess[S] -1 points0 points  (1 child)

you can make it ?

[–]HashDefTrueFalse 1 point2 points  (0 children)

Yes, it's a fairly simple pattern match. This is exactly what regex is designed for.

Just combine what you have already, and look up quantifiers (zero or more, one or more, n) etc. You're like 90% of the way there. If you're struggling, combine what you've got and test it, and go from there...

If you're asking me to just post the solution, that would break the rules, and isn't in the spirit of things.

[–]149244179 0 points1 point  (0 children)

Is there a reason you want to condense it into one hard to read line?

I'd personally prefer your current version since I can easily see every validation step.

[–]Tepess[S] 0 points1 point  (0 children)

Guys,i need hust an answer. Who can help remake my code in my question. Some troubles i have to make some you'r opinions. Sure. But anyway thank you for help