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

Bash正则中\w与$无法匹配模式的问题求助

问题排查与修复

你的脚本无法匹配的核心原因是Bash使用POSIX扩展正则表达式(ERE),不支持PCRE风格的\s和\w简写,而在线正则测试工具通常默认使用PCRE,导致两者行为不一致。

具体问题分析

  1. \s不被Bash识别:在ERE中,没有\s代表空白字符的语法,它会被当作字面量s处理。你的正则status:\s*(\w+)$实际在找status:后接零个或多个s,而非空白字符。
  2. \w非标准ERE语法:\w是PCRE的简写,ERE中需用[[:alnum:]](匹配字母数字)或[[:alnum:]_](含下划线)替代。

修复后的脚本

将正则替换为符合ERE标准的写法即可:

res=$(cat <<-EOM
Conducting pre-submission checks for my.zip and initiating connection to the Apple notary service...
Submission ID received
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
Successfully uploaded file
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
  path: path-to.zip
Waiting for processing to complete.
Current status: Invalid.....Processing complete
  id: 573ebf8c-5434-4820-86c6-46adf01f81a9
  status: Invalid
EOM
)

# Get status -- need word "invalid" from this line:  status: Invalid
status=""
# 使用ERE标准语法:[[:space:]]匹配空白,[[:alnum:]]匹配字母数字
regex='[[:space:]]*status:[[:space:]]*([[:alnum:]]+)$'
[[ $res =~ $regex ]] &&
  status=${BASH_REMATCH[1]}

echo "stat=$status"

额外优化方案(更直观)

如果你觉得正则调试麻烦,也可以用grep+awk组合提取目标值,可读性更强:

status=$(echo "$res" | grep -E '^[[:space:]]*status:' | tail -n1 | awk '{print $2}')
echo "stat=$status"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:17:56