簡體   English   中英

Python 正則表達式匹配字符串,其中包含由空格分隔的 3 個整數行“0 1 1”或“1 1 1”[暫停]

[英]Python regex to match the string which have 3 integers separated by spaces line “0 1 1” or “ 1 1 1” [on hold]

我正在嘗試匹配具有由空格分隔的 3 個整數“0 1 1”或“1 1 1”等的字符串。 我面臨的問題是,雖然我的正則表達式匹配“0 1 1”,但它也匹配“0 1 1 1”“0 1 1 1 1 1”等等。 我嘗試了各種方法,但沒有奏效。 誰能幫我用確切的正則表達式來匹配這個字符串。

如果您的字符串始終是由空格分隔的三個整數,那么這應該適合您:

re.match("^\d \d \d$", num_string)re.match()如果找到匹配項,則返回匹配 object,否則返回None 。)

通過將^$添加到正則表達式的開頭和結尾,您可以強制它僅在整個字符串包含 3 個整數且僅包含 3 個整數時才接受。 如果您期望前導/尾隨/不同的空格,您可以使用\s*代替。

演示在這里

根據您的評論(您需要識別 3 或 4 個 integer 字符串),您甚至不需要使用正則表達式。

在此處查看此代碼

s = [
    '0 1 1',
    '0 1 1 1',
    '0 1 1 1 1 1'
]
for x in s:
    y = x.split()
    if len(y) == 3:
        print(x)
        # 3 integer string logic goes here
    elif len(y) == 4:
        print(x)
        # 4 integer string logic goes here

此外,如果您想確保字符串的元素是數字,您可以使用isdigit()來確保每個列表元素都是數字。

在此處查看此代碼

s = [
    '0 1 1',
    '0 1 1 1',
    '0 1 1 1 1 1',
    '0 1 a'
]
for x in s:
    y = x.split()
    if all([z.isdigit() for z in y]):
        if (len(y) == 3):
            print(x)
            # 3 integer string logic goes here
        elif (len(y) == 4):
            print(x)
            # 4 integer string logic goes here

就像評論中提到的那樣,如果您的字符串恰好是由空格分隔的數字列表,請使用

r = re.compile("^\d+\s\d+\s\d+$")

如果你的模式也應該在一個更大的字符串中匹配,你需要使用前瞻和后瞻斷言來確保在 3-number-group 之前或之后都不存在另一個數字。

r = re.compile("(?<!\d\s)\d+\s\d+\s\d+(?!\s\d)")
s = "exactly 3 numbers matched 111 2 3 but not 4 3 2 1."
r.findall(s)

['111 2 3']

暫無
暫無

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

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