我正在尝试匹配格式为4.6或2.8的字符串中的版本号.我将在我的.bashrc文件中的函数中最终使用以下内容来查找操作系统版本:
function test () {
string="abc ABC12 123 3.4 def";
echo `expr match "$string" '[0-9][.][0-9]'`
}
Run Code Online (Sandbox Code Playgroud)
但是,这与字符串中的3.4不匹配.任何人都能指出我在正确的方向吗?
谢谢.
Ope*_*uce 11
首先,您可以删除echo- expr在任何情况下将其结果打印到stdout.
其次,你的正则表达式需要括号(否则它打印匹配的字符数,而不是匹配本身),它需要从头开始.*.
expr match "$string" '.*\([0-9][.][0-9]\)'
Run Code Online (Sandbox Code Playgroud)
从info expr页面:
STRING:REGEX'
Run Code Online (Sandbox Code Playgroud)Perform pattern matching. The arguments are converted to strings and the second is considered to be a (basic, a la GNU `grep') regular expression, with a `^' implicitly prepended. The first argument is then matched against this regular expression. If the match succeeds and REGEX uses `\(' and `\)', the `:' expression returns the part of STRING that matched the subexpression; otherwise, it returns the number of characters matched.
根据您的bash版本,不需要调用expr:
$ [[ "abc ABC12 123 3.4 def" =~ [0-9][.][0-9] ]] && echo ${BASH_REMATCH[0]}
3.4
Run Code Online (Sandbox Code Playgroud)