【问题标题】:Regex/Shell - how to match all except those with specific patternRegex/Shell - 如何匹配除具有特定模式的所有内容
【发布时间】:2021-02-17 11:08:53
【问题描述】:

我需要一个 shell 中的正则表达式来匹配除具有特定模式的字符串之外的所有字符串。

我的特定模式可以是可变的,即每个字符串中的 (i|I)[2 位数字](u|U)[2 位数字] 不应匹配。

例如:

Some.text.1234.text => 应该匹配
Some.text.1234.i10u20.text => 不应该匹配
Some.text.1234.I01U02.text => 不应该匹配
Some.text.1234.i83U23.text => 不应该匹配

【问题讨论】:

  • 您的意思是 i 而不是 t?您可以选择与[Ii][0-9][0-9][uU][0-9][0-9] 不匹配的字符串
  • 您提到shell,您使用什么工具来运行正则表达式?请分享相关代码。
  • @Thefourthbird,我的错,是的,我的意思是 i 而不是 t。
  • @WiktorStribiżew 我在 shell 脚本 (bash) 中使用正则表达式来匹配文件夹中的文件
  • 请将相关脚本部分添加到问题中。

标签: regex shell


【解决方案1】:

你可以试试:

^(?!.*[tuTU]\d{2}).*$

Demo

解释:

  1. ^一行的开头
  2. ?!.*负面展望
  3. [tuTU]\d{2}检查是否存在仅后2位的字符
  4. .*$ 如果先前的条件为负,则将整个字符串匹配到字符串结尾 $

【讨论】:

    【解决方案2】:

    检查字符串是否与正则表达式匹配的 Bash 脚本如下所示

    f='It_is_your_string_to_check';
    if [[ "${f^^}" =~ I[0-9]{2}U[0-9]{2} ]]; then
      echo "$f is invalid";
    else
       echo "$f is valid"
    fi;
    

    这里,"${f^^}" 将字符串转为大写(以免使用(U|u)(I|i)),然后=~ 运算符在此处触发正则表达式检查,因为右侧的模式没有被引用。您可以安全地使用它并使用单独的单引号字符串变量定义正则表达式模式并使用

    rx='I[0-9]{2}U[0-9]{2}'
    if [[ "${f^^}" =~ $rx ]]; then ...
    

    查看Bash demo online

    s='Some.text.1234.text
    Some.text.1234.i10u20.text
    Some.text.1234.I01U02.text
    Some.text.1234.i83U23.text'
    for f in $s; do
      if [[ "${f^^}" =~ I[0-9]{2}U[0-9]{2} ]]; then
        echo "$f is invalid";
      else
         echo "$f is valid"
      fi;
    done;
    

    输出:

    Some.text.1234.text is valid
    Some.text.1234.i10u20.text is invalid
    Some.text.1234.I01U02.text is invalid
    Some.text.1234.i83U23.text is invalid
    

    【讨论】:

    • 非常感谢您的回复。现在我想将 Some.text 和 1234 分开。我该怎么做?
    • @emmto 我不知道您对此的确切要求。试试extractrx='(.+)\.([0-9]+)\.[^.]+$' 然后if [[ "$f" =~ $extractrx ]]; then echo "Result: '${BASH_REMATCH[1]}' and '${BASH_REMATCH[2]}'",见the online demo
    猜你喜欢
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2010-12-13
    相关资源
    最近更新 更多