2011-04-02 30 views
1

我需要爲小型項目提出一個正則表達式。需要正則表達式的幫助:匹配如果某些字符串不以某些子模式開始並且某些字符不應該存在

該字符串不應該開始:

"/wiki" 

,它還應不具有以下圖案 "/.*:.*"(基本上圖案與字符「/」開頭並且存在的任何發生「:」之後)

,它也不能有一定的文字'#'

所以基本上所有這些字符串會失敗:

"/wiki/index.php?title=ROM/TAP&action=edit&section=2" 
"/User:romamns" 
"/Special:Watchlist" 
"/Space_Wiki:Privacy_policy" 
"#column-one" 

而所有這些字符串會通過:

"/ROM/TAP/mouse" 
"http://www.boost.org/" 

我將使用在Python正則表達式(如果讓任何區別)。

感謝您的任何幫助。

回答

5

^(/(?!wiki)[^:#]*|[^#/][^#]*)$應該沒問題,如測試here,當然我可能會遺漏一些東西,但是這似乎遵循您的規範。

+0

偉大的作品,謝謝先生。幾個小時後,我一直在爲此苦苦掙扎。 – bits 2011-04-03 00:03:17

+1

世界上什麼是「{1}」的目的? – hobbs 2011-04-03 00:12:47

+0

是的,多餘的「{1}」已經被淹沒了。另外:很高興我能幫上忙。 – nietaki 2011-04-03 00:16:23

0

如果您符合以下條件的正則表達式,那麼它應該失敗

^(\/wiki|.*?[\:#]) 
1

此測試腳本實現其精確匹配你們所要求的一個註釋的正則表達式:

import re 
def check_str(subject): 
    """Retturn True if subject matches""" 

    reobj = re.compile(
     """    # Match special string 
     (?!/wiki)   # Does not start with /wiki. 
     (?![^/]*/[^:]*:) # Does not have : following/
     [^#]*    # Match whole string having no # 
     $     # Anchor to end of string. 
     """, 
     re.IGNORECASE | re.MULTILINE | re.VERBOSE) 
    if reobj.match(subject): 
     return True 
    else: 
     return False 
     return False 

data_list = [ 
    r"/wiki/index.php?title=ROM/TAP&action=edit&section=2", 
    r"/User:romamns", 
    r"/Special:Watchlist", 
    r"/Space_Wiki:Privacy_policy", 
    r"#column-one", 
    r"/ROM/TAP/mouse", 
    r"http://www.boost.org/", 
    ] 
cnt = 0 
for data in data_list: 
    cnt += 1 
    print("Data[%d] = \"%s\"" % 
     (cnt, check_str(data))) 
相關問題