正则表达式匹配bash变量 [英] regex match bash variable
问题描述
我正在尝试修改bash脚本.脚本当前包含
I am trying to modify a bash script. The script current contains
print "<div class=\"title\">" $1 "</div>"
$ 1
可能如下所示:
Apprentice Historian (Level 1)
Historian (Level 4)
Master Historian (Level 7)
我想做的是添加一个名为"base"值的图像.我有这样的想法:
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\" $1 ".png\"></div><div class=\"title\">" $1 "</div>"
但是,在这种情况下,我希望 $ 1
只返回 Historian
.我当时想我可以使用正则表达式来匹配和匹配 $ 1
并仅保留我需要的部分.
However, in this case I'd like $1
to only return Historian
. I was thinking I could use a regex to match and on $1
and keep only the part I need.
(Apprentice|Master)?\s(.*)\s(\(Level \d\))
我知道我的正则表达式还不存在,理想情况下,学徒/大师将在他们自己的比赛组中,而不是与基地打成一片.而且我不知道如何匹配 $ 1
参数.
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 $1
argument.
推荐答案
在bash中使用正则表达式匹配:
Using regex matching in bash:
for a in 'Apprentice Historian (Level 1)' 'Historian (Level 4)' 'Master Historian (Level 7)' ; do
set "$a"
echo " === $1 ==="
[[ $1 =~ (Apprentice|Master)?' '?(.*)' ('Level' '[0-9]+')' ]] \
&& echo ${BASH_REMATCH[${#BASH_REMATCH[@]}-1]}
done
棘手的部分是从BASH_REMATCH检索正确的成员.Bash不支持非捕获括号,因此Historian小于1或2.幸运的是,我们知道它是最后一个.
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变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!