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

在RegExp工具中验证字符串时,RegExp测试失败

  •  0
  • Jazzschmidt  · 技术社区  · 11 月前

    我有一个小的正则表达式,它应该验证提交主题是否符合ReactJS提交消息格式。由于该表达式适用于我的测试字符串,因此代码让我感到困惑。

    这个小例子应该再现这种行为:

    #!/bin/bash
    
    function test_subject {
      local subject="$1"
      local pattern="^(feat|fix|docs|style|refactor|test|chore)\([a-zA-Z0-9._-]+\): [^\n]+$"
    
      if ! [[ $subject =~ $pattern ]]; then
        echo "Invalid subject: $subject"
      else
        echo "  Valid subject: $subject"
      fi
    }
    
    test_subject "chore(gh-actions): add script for commit check"
    test_subject "chore(gh-actions): add script for commit checking"
    test_subject "feat(ABC-123): add new feature"
    test_subject "fix(ABC123): add new feature"
    test_subject "fix(ABC123): fix previously added feature"
    test_subject "fix(scope): fix bug"
    

    这将导致以下输出:

      Valid subject: chore(gh-actions): add script for commit check
    Invalid subject: chore(gh-actions): add script for commit checking
    Invalid subject: feat(ABC-123): add new feature
    Invalid subject: fix(ABC123): add new feature
      Valid subject: fix(ABC123): fix previously added feature
      Valid subject: fix(scope): fix bug
    
    2 回复  |  直到 11 月前
        1
  •  2
  •   anubhava    11 月前

    您将需要使用 . 而不是 [^\n] 在shell正则表达式中匹配任何字符。

    n 正在评估为 [^n] 即除以下字符之外的任何字符 n 你的示例字符串2、3、4有字母 n 匹配后的某个地方 : .

    这应该对你有用:

    test_subject() {
      local subject="$1"
      local pattern="^(feat|fix|docs|style|refactor|test|chore)\([a-zA-Z0-9._-]+\): .+$"
    
      if ! [[ $subject =~ $pattern ]]; then
        echo "Invalid subject: $subject"
      else
        echo "  Valid subject: $subject"
      fi
    }
    
    test_subject "chore(gh-actions): add script for commit check"
    test_subject "chore(gh-actions): add script for commit checking"
    test_subject "feat(ABC-123): add new feature"
    test_subject "fix(ABC123): add new feature"
    test_subject "fix(ABC123): fix previously added feature"
    test_subject "fix(scope): fix bug"
    

    输出:

      Valid subject: chore(gh-actions): add script for commit check
      Valid subject: chore(gh-actions): add script for commit checking
      Valid subject: feat(ABC-123): add new feature
      Valid subject: fix(ABC123): add new feature
      Valid subject: fix(ABC123): fix previously added feature
      Valid subject: fix(scope): fix bug
    
        2
  •  1
  •   White Owl    11 月前

    Bash正则表达式不知道 \n 成为新线角色。这个 [^\n] 只是一个 [^n] 因此,脚本标记为无效的行中有“n”(“checking”、“new”)。

    bash-regexp识别的新行实际上是 $ -线的尽头。

    另一点-您的测试字符串没有 n 其中包含字符,因此没有必要检查其是否存在,因此简单 <complex_pattern>: .+ 这就足够了,这意味着复杂的模式以冒号、空格结束,之后还有其他内容。没有必要以以下方式结束模式 $ 因为它已经到达字符串的末尾。

    说。。。如果你在模式中点击Enter,你会得到一个字符串,比如:

      local pattern="^(feat|fix|docs|style|refactor|test|chore)\([a-zA-Z0-9._-]+\): [^
    ]+$"
    

    但布什(或至少是它的某些版本)会将其视为一个带有 n 并在字符串内做一个真正的“否”。

    这是可能的——是的。这比简单好吗 .+ -绝对不是。但作为一个有趣的功能和可能混淆人们的方式——是的。