Bash中不区分大小写的正则表达式 [英] Case insensitive regex in Bash

查看:137
本文介绍了Bash中不区分大小写的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪种方法更好地检查var(由用户在键盘上输入)是否以不区分大小写的方式与正则表达式匹配。我知道有一些不同的可能性。示例:我想要一个正则表达式,匹配一个空值和所有以下列表: Y N y n

I want to know which method is better to check if a var (input by user on keyboard) matches with a regex in a case insensitive way. I know there are some different possibilities. Example: I want a regex matching an empty value and all of this list: Y, N, y, n, Yes, No, YES, NO

我搜索了不同的方法。不知道是否会更好。我会把它们中的一些给我用。

I searched looking different methods. Not sure if could be another better. I'll put a couple of them working for me.


  • 第一个是有点棘手的,全部设置为大写比较:

  • First one is a little "tricky" setting all to uppercase for the comparison:

#!/bin/bash
yesno="null" #any different value for initialization is valid
while [[ ! ${yesno^^} =~ ^[YN]$|^YES$|^NO$|^$ ]]; do
    read -r yesno
done


  • 第二个正在使用 shopt -s nocasematch 。但不确定这样做之后是否可以还原,因为我不想为所有脚本设置它。

  • Second one is using shopt -s nocasematch. But not sure if after doing that it can be reverted because I don't want to set this for all the script.

    #!/bin/bash
    yesno="null" #any different value for initialization is valid
    shopt -s nocasematch
    while [[ ! ${yesno} =~ ^[yn]$|^yes$|^no$|^$ ]]; do
        read -r yesno
    done
    


  • 这些正则表达式可以通过任何方式得到改进吗?
    是否有更好(更优雅)的方法?
    在第二种方法上,是否有办法还原该设置?

    Can these regex get improved in any way? Is there a better (more elegant) method? On second method, is there a way to revert that setting?

    推荐答案

    shopt 是一个好方法,因为您可以将最初输入的值保留在变量 yesno 中。

    shopt is good approach as you are able to retain originally entered value in variable yesno.

    您只需稍微重构一下正则表达式即可:

    You can just refactor your regex a bit:

    #!/bin/bash
    
    yesno="null"
    
    # set nocasematch option
    shopt -s nocasematch
    
    while [[ ! ${yesno} =~ ^([yn]|yes|no)?$ ]]; do
        read -r -p "Enter a yes/no value: " yesno
    done
    
    # unset nocasematch option
    shopt -u nocasematch
    
    # examine your variable
    declare -p yesno
    

    这篇关于Bash中不区分大小写的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆