简体   繁体   中英

Check string by user-given regex

I one of my Django app, I need to make a string validation using flags. What I mean: in admin panel, I add for example:

  • baduser*@gmail.com
  • spambot-?@gmail.com

etc...

There won't be strict pythonic regex, but '*' or '?' provided by common admin

While someone is signing up, i must check all that credentials by Python regex. I need to check:

  • * as any sign, one or multiple times
  • ? as 1 sign.

Any ideas how could I make that?

You'd translate that to a regular expression, then use that to match against email addresses.

That's not that hard to do:

import re

def translate_pattern(pattern):
    res = []
    for c in pattern:
        if c == '*':
            res.append('.+')  # 1 or more
        elif c == '.':
            res.append('.')   # exactly 1
        else:
            res.append(re.escape(c))  # anything else is a literal character
    return re.compile(''.join(res))

The function returns ready-compiled regular expressions:

>>> translate_pattern('baduser*@gmail.com').search('baduser12345@gmail.com')
<_sre.SRE_Match object at 0x107467780>
>>> translate_pattern('baduser*@gmail.com').search('gooduser@gmail.com')

Do note that because you match on . as any character, the following matches too:

>>> translate_pattern('baduser*@gmail.com').search('baduser12345@gmail-com')
<_sre.SRE_Match object at 0x1074677e8>

because the . matches the - in gmail-com .

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