Bash:使用正则表达式检查字符串是否看起来像三部分版本号

时间:2023-01-19 17:10:39

I need bash to check whether CI_COMMIT_REF_NAME matches either the string master, or a three part version number like 1.3.5, 1.1.11 and so on.

我需要bash来检查CI_COMMIT_REF_NAME是匹配字符串master还是三部分版本号(如1.3.5,1.1.11等)。

Here's what I tried:

这是我尝试过的:

#!/bin/bash
CI_COMMIT_REF_NAME=1.1.4
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]]
 then 
     echo "true"
 else 
     echo "false"
fi

The expected output is true, but I get false. Setting the variable to master works as intended, so the mistake must be my regex.

预期的输出是真的,但我弄错了。将变量设置为master可以按预期工作,因此错误必须是我的正则表达式。

What am I doing wrong?

我究竟做错了什么?

2 个解决方案

#1


1  

You need to declare the regex as a separate variable inside single quotes, there will be no issues parsing your regex in bash then and make sure the parentheses are placed around the [0-9]{1,2}\. part:

你需要在单引号中将正则表达式声明为单独的变量,然后在bash中解析正则表达式时没有问题,并确保括号放在[0-9] {1,2} \周围。部分:

rx='^([0-9]{1,2}\.){2}[0-9]{1,2}$'
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ $rx ]]

See the online Bash demo

查看在线Bash演示

Now, the pattern matches:

现在,模式匹配:

  • ^ - start of string
  • ^ - 字符串的开头

  • ([0-9]{1,2}\.){2} - 2 occurrences of 1 or 2 digits followed with a literal dot
  • ([0-9] {1,2} \。){2} - 出现1或2位数,后跟一个文字点

  • [0-9]{1,2} - 1 or 2 digits
  • [0-9] {1,2} - 1或2位数

  • $ - end of string.
  • $ - 结束字符串。

#2


1  

You probably don't want to match the beginning of the line twice:

您可能不希望两次匹配行的开头:

$ CI_COMMIT_REF_NAME=1.1.4
$ [[ $CI_COMMIT_REF_NAME =~ (^[0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
$ [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
match

#1


1  

You need to declare the regex as a separate variable inside single quotes, there will be no issues parsing your regex in bash then and make sure the parentheses are placed around the [0-9]{1,2}\. part:

你需要在单引号中将正则表达式声明为单独的变量,然后在bash中解析正则表达式时没有问题,并确保括号放在[0-9] {1,2} \周围。部分:

rx='^([0-9]{1,2}\.){2}[0-9]{1,2}$'
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ $rx ]]

See the online Bash demo

查看在线Bash演示

Now, the pattern matches:

现在,模式匹配:

  • ^ - start of string
  • ^ - 字符串的开头

  • ([0-9]{1,2}\.){2} - 2 occurrences of 1 or 2 digits followed with a literal dot
  • ([0-9] {1,2} \。){2} - 出现1或2位数,后跟一个文字点

  • [0-9]{1,2} - 1 or 2 digits
  • [0-9] {1,2} - 1或2位数

  • $ - end of string.
  • $ - 结束字符串。

#2


1  

You probably don't want to match the beginning of the line twice:

您可能不希望两次匹配行的开头:

$ CI_COMMIT_REF_NAME=1.1.4
$ [[ $CI_COMMIT_REF_NAME =~ (^[0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
$ [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
match