regex - Bash 脚本正则表达式

标签 regex bash unix

我正在尝试从格式为 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/

相关文章:

php - PHP 中的正则表达式帮助

mysql - 精确时间之间的查询

linux - 在不知道目录名称的情况下打开目录

bash - 如何使用 grep 在当前目录中搜索具有给定字符串的所有文件,然后将这些文件移动到新文件夹中?

c++ 字符串到 ipAddress windows/unix 系统

python:多行正则表达式

ios - swift 正则表达式格式?

c - unix goto命令源代码

java - 具有重复的正则表达式排列

相当于 bash 字符串操作的 Windows bat 文件