Regular Expression in Bash Script

后端 未结 1 966
一整个雨季
一整个雨季 2021-02-02 08:33

Hello awesome community,

I\'m a complete dope when it comes to regex. I\'ve put off learning it.. and now my laziness has caught up with me.

What I\'m trying to

相关标签:
1条回答
  • 2021-02-02 08:45

    =~ succeeds if the string on the left contains a match for the regex on the right. If you want to know if the string matches the regex, you need to "anchor" the regex on both sides, like this:

    regex='^[0-9][0-9][_][0-9][0-9][_][0-9][0-9]$'
    if [[ $incoming_string =~ $regex ]]
    then
      # Do awesome stuff here
    fi
    

    The ^ only succeeds at the beginning of the string, and the $ only succeeds at the end.

    Notes:

    1. I removed the unnecessary () from the regex and "" from the [[ ... ]].
    2. The bash manual is poorly worded, since it says that =~ succeeds if the string matches.
    0 讨论(0)
提交回复
热议问题