正则表达式匹配 bash 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9289239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regex match bash variable
提问by Brombomb
I am trying to modify a bash script. The script current contains
我正在尝试修改 bash 脚本。脚本当前包含
print "<div class=\"title\">" "</div>"
Where $1may look like:
哪里$1可能看起来像:
Apprentice Historian (Level 1)
Historian (Level 4)
Master Historian (Level 7)
What i'd like to do is add an image which is named the "base" value. I had something like this in mind:
我想要做的是添加一个名为“基本”值的图像。我有这样的想法:
print "<div class=\"icon\"><imgsrc=\"icons\" ".png\"></div><div class=\"title\">" "</div>"
However, in this case I'd like $1to only return Historian. I was thinking I could use a regex to match and on $1and keep only the part I need.
但是,在这种情况下,我$1只想返回Historian. 我在想我可以使用正则表达式来匹配并$1只保留我需要的部分。
(Apprentice|Master)?\s(.*)\s(\(Level \d\))
I know my regex isn't quite there, ideally apprentice/master would be in their own match group and not tied the base. And I don't know how to match on the $1argument.
我知道我的正则表达式不完全存在,理想情况下,学徒/大师应该在他们自己的比赛组中,而不是在基础上。我不知道如何匹配$1论点。
回答by choroba
Using regex matching in bash:
在 bash 中使用正则表达式匹配:
for a in 'Apprentice Historian (Level 1)' 'Historian (Level 4)' 'Master Historian (Level 7)' ; do
set "$a"
echo " === ==="
[[ =~ (Apprentice|Master)?' '?(.*)' ('Level' '[0-9]+')' ]] \
&& echo ${BASH_REMATCH[${#BASH_REMATCH[@]}-1]}
done
The tricky part is to retrieve the correct member from BASH_REMATCH. Bash does not support non-capturing parentheses, therefore Historian is either under 1 or 2. Fortunately, we know it is the last one.
棘手的部分是从 BASH_REMATCH 中检索正确的成员。Bash 不支持非捕获括号,因此 Historian 要么低于 1,要么低于 2。幸运的是,我们知道它是最后一个。
回答by user unknown
Samples pure shell:
样品纯壳:
a="Historian (Level 1)"
noParens=${a/ \(*/}
lastWord=${noParens/[A-Za-z]* /}
a="Muster Historian (Level 1)"
noParens=${a/ \(*/}
lastWord=${noParens/[A-Za-z]* /}
(It's the same expressions in both cases, just repeated for easy testing).
(两种情况下的表达式相同,只是为了便于测试而重复)。
回答by Kristofer
Based on "And I don't know how to match on the $1 argument."
基于“我不知道如何匹配 $1 参数。”
Have I understood you correctly if what you are asking for is not whether your regex is correct but rather how to perform the match against the contents of your bash variable?
如果您要求的不是您的正则表达式是否正确,而是如何根据 bash 变量的内容执行匹配,我是否正确理解您?
matched_text=$(echo $yourbashvariablecontainingthetext | sed 's/your_regex/backreference_etc/')
$yourbashvariablecontainingthetext should be your $1
$yourbashvariable containsthetext 应该是你的 $1

