【问题标题】:Matching inputs with a regular expression in Python [duplicate]用Python中的正则表达式匹配输入[重复]
【发布时间】:2013-03-01 15:49:39
【问题描述】:

我有一个程序需要输入“是”,例如:

my_input = raw_input('> ')
if my_input == 'yes':
    #etc

但这太具体了,我希望输入匹配这个正则表达式:[yY](es)?,这样如果用户输入“是,是,y 或 Y”,它是相同的。但我不知道这在python中是如何实现的。

我想要类似的东西:

regex = some.regex.method('[yY](es)?')
my_input = raw_input('> ')
if my_input == regex:
    #etc  

提前谢谢你。

【问题讨论】:

    标签: python regex input match


    【解决方案1】:

    Regex 在这里可能有点矫枉过正,但这是一种方法:

    import re
    regex = re.compile(r'y(es)?$', flags=re.IGNORECASE)
    my_input = raw_input('> ')
    if regex.match(my_input):
        #etc 
    

    这将匹配字符串 "y" 或 "yes" 与任何大小写,但对于像 "yellow" 或 "yesterday" 这样的字符串将失败。

    或者更好的是,没有正则表达式的相同行为:

    my_input = raw_input('> ')
    if my_input.lower() in ('y', 'yes'):
        #etc
    

    【讨论】:

    • 谢谢,我想我还是坚持使用元组方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多