use*_*141 2 python regex input match
我有一个程序需要输入“是”,例如:
my_input = raw_input('> ')
if my_input == 'yes':
#etc
Run Code Online (Sandbox Code Playgroud)
但这太具体了,我希望输入与此正则表达式匹配:[yY](es)?,以便如果用户输入“是,是,y 或 Y”,则是相同的。但我不知道这是如何在 python 中实现的。
我想要这样的东西:
regex = some.regex.method('[yY](es)?')
my_input = raw_input('> ')
if my_input == regex:
#etc
Run Code Online (Sandbox Code Playgroud)
先感谢您。
正则表达式在这里可能有点矫枉过正,但这是一种方法:
import re
regex = re.compile(r'y(es)?$', flags=re.IGNORECASE)
my_input = raw_input('> ')
if regex.match(my_input):
#etc
Run Code Online (Sandbox Code Playgroud)
这将匹配字符串"y"或"yes"任何情况,但对于像"yellow"或这样的字符串将失败"yesterday"。
或者更好的是,没有正则表达式的相同行为:
my_input = raw_input('> ')
if my_input.lower() in ('y', 'yes'):
#etc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2754 次 |
| 最近记录: |