Warm tip: This article is reproduced from serverfault.com, please click

regex-无法使用grep-command和正则表达式提取jdk-version

(regex - Could not extract jdk-version using grep-command and regular expressions)

发布于 2020-11-29 13:33:13

我想提取的版本jdk使用regular-expressions其实我有以下版本:

openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04)
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04, mixed mode,sharing)

我写了正则表达式。看起来如下: ^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}$

此正则表达式可用于在线正则表达式测试器https://regex101.com/)。不幸的是,它不能与grep-command一起使用。我正在使用扩展的正则表达式我的用于提取jdk-version的代码如下所示:

CMD_RESULT=$(java --version 2>&1 | head -n 1 | cut -d '' -f 2)
if [ ! -z "$CMD_RESULT" ]
then 
    for token in $CMD_RESULT
    do
       JAVA_VERSION=$(echo $token |  grep -e $VERSION_EXTRACTION_REGEX)
       if [ ! -z  $JAVA_VERSION ];
       then
            printf "${GREEN}Java version: [$JAVA_VERSION]\n"
       fi
     done
fi

我不明白,为什么我的正则表达式无法使用grep-command进行在线正则表达式检查器。我正在使用参数-e扩展正则表达式。

任何的想法 ?

Questioner
user14729562
Viewed
11
markp-fuso 2020-11-30 00:52:58

对OP当前代码的一些小改动:

  • 如在评论中提到的,^$代表开始和输入结束; 从正则表达式中删除这些
  • 虽然grep可以使用生成的正则表达式,但有必要告诉它grep-Extended正则表达式模式运行
  • 我们可以使用grep's -ooption将输出限制为仅与正则表达式匹配的部分

样本输入数据:

$ cat jdk.dat
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04)
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-Ubuntu-0ubuntu1.18.04, mixed mode,sharing)

grep使用OP的修改后的正则表达式的一种解决方案:

$ grep -oE '[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}' jdk.dat
11.0.9.1
11.0.9.1
11.0.9.1

同样的事情,但将正则表达式存储在OPs变量中:

$ VERSION_EXTRACTION_REGEX='[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}'
$ grep -oE "${VERSION_EXTRACTION_REGEX}" jdk.dat
11.0.9.1
11.0.9.1
11.0.9.1

注意:我将由用户决定要使用哪个值,例如head -n 1仅与第一输入行(openjdk 11.0.9.1 2020-11-04)一起使用