regex Bash正则表达式与带有\w和$的模式不匹配

wz1wpwve  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(88)

我刚加入巴斯有人能告诉我我做错了什么吗?我在网上尝试了下面的正则表达式模式,它工作得很好。但是下面的Bash脚本拒绝匹配。
我需要从文本块的最后一行提取status:的值,如下所示:

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=""
regex='status:\s*(\w+)$'
[[ $res =~ $regex ]] &&
  status=${BASH_REMATCH[1]}

echo "stat=$status"
7rtdyuoh

7rtdyuoh1#

x1c 0d1x您的bash版本不支持类似PCRE的语法\w
我会怎么做:

#!/usr/bin/env bash

# let's KISS: Keep It Simple Stupid
res='
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
'

# Get status -- need this one:  status: Invalid
status=""
regex='status:[[:space:]]*([[:word:]]+)'
[[ $res =~ $regex ]] && status=${BASH_REMATCH[1]}

echo "stat=$status"
输出
stat=Invalid
正则表达式匹配如下:
节点解释
status:'状态:'
[[:space:]]*任何字符:空格字符(如\s)(0或更多次(匹配最大可能数量))
(分组并捕获到\1:
[[:word:]]+任何字符:字母数字和下划线字符(如\w)(1次或多次(匹配可能的最大数量))
)结束\1

有关POSIX * 字符类 * 的文档,请参阅POSIX规范的

相关问题