You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中验证ReactJS提交信息的正则匹配异常排查

问题原因及解决办法

问题根源

你的Bash脚本里正则匹配异常有两个核心原因:

  • 双引号导致正则元字符失效:Bash的[[ =~ ]]语法中,若正则表达式被双引号包裹,像+这类扩展正则元字符会被当成普通文本处理,失去"匹配一次或多次"的作用。
  • \n的解析错误:Bash正则里\n不会被解析为换行符,而是字面的字符n。你写的[^\n]+实际是匹配"除了字母n之外的任意字符",这就导致带"checking"(包含n)的字符串直接匹配失败。

修复后的脚本

把正则表达式的双引号去掉,同时把[^\n]+替换为.*(因为提交主题是单行内容,.*可以匹配行尾前的所有字符):

#!/bin/bash

function test_subject {
  local subject="$1"
  # 去掉双引号,替换[^\n]+为.*
  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,完全符合预期。

内容的提问来源于stack exchange,提问作者Jazzschmidt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:10:06