簡體   English   中英

需要正則表達式幫助:如果某些字符串不是以某些子模式開頭並且某些字符不應該存在,則匹配

[英]Need regex help: Match if certain string doesn't start with certain sub-patterns AND certain character should not be there

我需要為一個小型項目想出一個正則表達式。

該字符串不應以以下內容開頭:

"/wiki"

並且它也不應具有以下模式"/.*:.*" (基本上模式以char'/'開頭,此后出現任何':')

並且它也不能有某個字符'#'

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

"/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中使用正則表達式(如果有任何區別)。

謝謝你的幫助。

^(/(?!wiki)[^:#]*|[^#/][^#]*)$應該沒問題,因為測試在這里 ,當然我可能失去了一些東西,但是這似乎是按照你的規范。

經過測試的腳本實現了一個注釋正則表達式,該正則表達式完全符合您聲明的要求:

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

如果匹配以下正則表達式,則它應該失敗

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM