代码之家  ›  专栏  ›  技术社区  ›  pyeR_biz

regex区分字符串中所有字符和少数字符的大写字母

  •  1
  • pyeR_biz  · 技术社区  · 6 年前

    我必须将一个字符串传递到程序中,根据字符串的不同,它只返回一个响应值。我在为两个案例构建模式时遇到困难。

    • 如果字符串以“?”结尾而且是 不是全部大写 返回“x”,不管字符串的内容是什么。
    • 如果字符串以“?”结尾而且是 全部大写 返回“Y”。

    • 如果字符串以“!”结尾或 都是大写的 (结尾没有问号)返回“Z”。

    • 如果字符串只是空白,则返回“a”。

    下面是两个示例字符串,它们是四个独立的模式-

    phrase1 = "Simple String with some UPPercase in Between ends with?"
    phrase2 = "BIG STRING ALL CAPS ENDS WITH?" 
    phrase3_a = "ALLCAPSSTRING NOTHING AT THE END OF STRING" 
    phrase3_b = "Any String with ALL UPPERCASE (or not) but ends with!"
    phrase4 = "\t\t\t\t"
    

    我还没有建立准确的模式,这就是我要问的。之后我打算用一个 re.compile 所有模式,然后 finditer 使用非“无”组。在下面的代码中,我删除了 whitespaces ,因为如果其他模式都不匹配,则匹配空白模式 [\s] 不退货,我可以单独使用-

    phrase=re.sub(r'[\s]','',phrase)
    
    pattern_phrase1 = re.compile (r'[a-zA-Z0-9]\?$')
    pattern_phrase2 = re.compile (r'[A-Z0-9]\?$')    
    pattern_phrase3 = re.compile (r'[A-Z]|[.!$]')
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   pyeR_biz    6 年前

    解决方案1-使用ISX函数

        def hey(phrase):
            responses ={'ques':x,'ques_yell':y,'yell':z,'onlycall':b,'what':c}
            phrase=''.join(phrase.split())
    
            if phrase=='':
                return responses['onlycall']
    
            if phrase.isupper():
                if phrase[-1]=='?':
                    return responses['ques_yell']
                return responses['yell']
            elif not phrase.isupper():
                if phrase[-1]=='?':
                    return responses['ques']
            return responses['what']