我有一个小的正则表达式,它应该验证提交主题是否遵循 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
您需要在 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