正则表达式的新功能。我下面的正则表达式会出现三个问号,并且会连续出现更多的问号,但是如果我想在两个数字之间出现三个问号(总和为10,而不问它们是否连续出现),怎么办?

import re


def has_three_question_marks(word):
    regex_pattern = re.compile(r"(\d\D+)(?=(\d))")
    question_marks = re.compile(r"\d(\D+)?\?{3,}(\D+)?")
    matches = re.findall(regex_pattern, word)
    if matches:
        for match in matches:
            question_mark_matches = re.findall(question_marks, str(match))
            if question_mark_matches:
                if int(match[0][0]) + int(match[1]) == 10:
                    return True
                continue
    return False
has_three_question_marks("arrb6???4xxbl5???eee5") #This returns True
has_three_question_marks("acc?7??sss?3rr1??????5") #This returns False, I need it to return True

最佳答案

更好的方法(紧随其后):

import re
def splitting(text):
    n = re.split("\d","a"+text+"a") # make sure it does not start/end with ?
    q = [ques for ques in n if re.match("^\?+$",ques)]
    return sum(len(qq) for qq in q) > 2


test = ["arrb6???4xxbl5???eee5","acc?7??sss?3rr1??????5",
        "?5?5?5?", "1???1", "1?1?1?1","1??2?", "1??2?2","1??23?2"]

for t in test:
    print(f"{t:<22} {splitting(t)}")


输出:

arrb6???4xxbl5???eee5  True
acc?7??sss?3rr1??????5 True
?5?5?5?                False
1???1                  True
1?1?1?1                True
1??2?                  False
1??2?2                 True
1??23?2                True




我不太了解正则表达式是否是您的工具。正则表达式无法检测到重叠模式:

'1?1?1?1' --> false


您可以这样做:

import re

test = ["arrb6???4xxbl5???eee5","acc?7??sss?3rr1??????5",
        "?5?5?5?", "1???1", "1?1?1?1","1??2?", "1??2?2","1??23?2"]


def areThreeIn(text):
    patt = r"\d(\?+)\d"
    matches = re.findall(patt,text)
    return sum(len(m) for m in matches) >= 3

for t in test:
    print(f"{t:<20} {areThreeIn(t)}")


输出:

arrb6???4xxbl5???eee5 True
acc?7??sss?3rr1??????5 True
?5?5?5?              False
1???1                True
1?1?1?1              False
1??2?                False
1??2?2               False # overlapping: would be True
1??23?2              True

关于python - 检查三个问号之间是否出现三个问号(总和为10),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52349159/

10-13 05:39