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

问题描述 投票:0回答:1

我有一个小的正则表达式,它应该验证提交主题是否遵循 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
regex bash sh
1个回答
0
投票

您需要在 shell 正则表达式中使用

.
而不是
[^\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
© www.soinside.com 2019 - 2024. All rights reserved.