我正在尝试从格式为 4.6 或 2.8 的字符串中匹配版本号。我有以下内容,我最终将在我的 .bashrc 文件中的函数中使用它来查找操作系统版本:
function test () {
string="abc ABC12 123 3.4 def";
echo `expr match "$string" '[0-9][.][0-9]'`
}
但是,这与字符串中的 3.4 不匹配。谁能在这里指出我正确的方向?
谢谢。
最佳答案
首先,您可以删除 echo
- expr
在任何情况下都会将其结果打印到标准输出。
其次,您的正则表达式需要括号(否则它会打印匹配的字符数,而不是匹配本身),并且它需要以 .*
开头。
expr match "$string" '.*\([0-9][.][0-9]\)'
来自 info expr
页面:
STRING : REGEX'
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.
关于regex - Bash 脚本正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7159441/