本文介绍了Bash 在字符串上使用匹配正则表达式和后视模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash --version

GNU bash,版本 3.2.57(1)-release (x86_64-apple-darwin19)

说明:

我想从这个字符串字典中提取 WorkingDir 键值:

I want to extract the WorkingDir key value from this string dictionary:

config="""
"TerraformCommand": "terragrunt-info",
  "WorkingDir": "usr/terraform-modules/terraform-aws-codebuild/examples/.terragrunt-cache/xh9X2WgTwVjjRHiPBjKUl0Lr86w/SGN8gG45haGoXT7IhOh9_iuKkbc"
}
"""

在这种情况下,预期的输出是:

In this case, the expected output would be:

"usr/terraform-modules/terraform-aws-codebuild/examples/.terragrunt-cache/xh9X2WgTwVjjRHiPBjKUl0Lr86w/SGN8gG45haGoXT7IhOh9_iuKkbc"

尝试:

到目前为止,我已经尝试过使用这种正向后视/前瞻模式的不同方法:'(?<=("WorkingDir":s")).+(?=")'1.

So far I've tried using different methods using this positive lookbehind/lookahead pattern: '(?<=("WorkingDir":s")).+(?=")'1.

echo `expr "$config" : '(?<=("WorkingDir":s")).+(?=")'`

输出:0

2.

pat='(?<=("WorkingDir":s")).+(?=")'
[[ $config =~ $pat ]]
echo "${BASH_REMATCH[0]}"
echo "${BASH_REMATCH[1]}"

输出:


echo $config | grep -o '(?<=("WorkingDir":s")).+(?=")'

输出:

推荐答案

正如评论中所指出的,expr 只使用basic";(又名过时")正则表达式,并且 bash 的 =~ 运算符使用的正则表达式引擎不支持前瞻或后视(或 s 空格的简写)).但是你不需要环顾四周,只需匹配一切并使用捕获组来挑选你想要的部分(并将模式存储在一个变量中以避免可能的解析不一致):

As was pointed out in the comments, expr only uses "basic" (aka "obsolete") regular expressions, and the regex engine that bash's =~ operator uses doesn't support lookahead or lookbehind (or the s shorthand for space either). But you don't need lookaround, just match everything and use a capture group to pick out the part you want (and store the pattern in a variable to avoid possible parsing inconsistencies):

WorkingDirPattern='"WorkingDir":[[:space:]]"([^"]+)"'
if [[ "$config" =~ $WorkingDirPattern ]]; then
    WorkingDir="${BASH_REMATCH[1]}"    # get the contents of the first capture group
    echo "WorkingDir is $WorkingDir"
else
    echo "No WorkingDir found" >&2
fi

这篇关于Bash 在字符串上使用匹配正则表达式和后视模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:30