2013-02-25 28 views
0

我的一個Django應用程序,我需要使用標誌進行字符串驗證。我的意思是:在 管理面板,我添加了例如:用戶給出的正則表達式檢查字符串

等等

不會有嚴格的Python的正則表達式,但' *' 要麼 '?'由普通管理員提供

有人註冊時,我必須通過Python正則表達式檢查所有憑據。 我需要檢查:

  • *任何標誌,一次或多次
  • ?爲1米的標誌。

任何想法我怎麼能做到這一點?

+1

是'baduser @ gmailxcom'的有效地址還是隻對用戶名有效的標誌? – eumiro 2013-02-25 11:42:05

+0

baduser*@gmail.com是由管理員提供的字符串。該表達應該阻止例如:[email protected],[email protected]等。 我必須以某種方式轉義有效的電子郵件標誌,如'。'。和'+'是正則表達式中的特殊字符。 – tunarob 2013-02-25 11:56:41

回答

5

你會把它翻譯成正則表達式,然後用它來匹配電子郵件地址。

這並不難做到:

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)) 

該函數返回準備編譯的正則表達式:

>>> translate_pattern('baduser*@gmail.com').search('[email protected]') 
<_sre.SRE_Match object at 0x107467780> 
>>> translate_pattern('baduser*@gmail.com').search('[email protected]') 

請注意,由於您的.任何字符匹配,以下匹配太:

>>> translate_pattern('baduser*@gmail.com').search('[email protected]') 
<_sre.SRE_Match object at 0x1074677e8> 

,因爲.匹配gmail-com中的-

+0

聽起來像一個很好的解決方案:) – tunarob 2013-02-25 13:40:43

相關問題