[英]Check string by user-given regex
I one of my Django app, I need to make a string validation using flags. 我是我的Django应用程序之一,我需要使用标志进行字符串验证。 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 '?' 不会有严格的pythonic正则表达式,但是'*'或'?' provided by common admin
由普通管理员提供
While someone is signing up, i must check all that credentials by Python regex. 有人注册时,我必须通过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
. 匹配
gmail-com
中的-
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.