Linux Bash 脚本中的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17028143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:10:51  来源:igfitidea点击:

Regular Expression in Bash Script

regexlinuxbashexpression

提问by Robbie

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 do:
Check if a string matches this format:

我想要做的是:
检查字符串是否与此格式匹配:

10_06_13

ie. Todays date, or a similar date with "2digits_2digits_2digits"

IE。今天的日期,或与“2digits_2digits_2digits”类似的日期

What I've done:

我所做的:

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

This works to a certain extent. But when the incoming string equals 011_100_131... it still passes the regex check.

这在一定程度上起作用。但是当传入的字符串等于011_100_131......它仍然通过正则表达式检查。

I'd be grateful if anyone could help point me in the right direction.
Cheers

如果有人能帮助我指出正确的方向,我将不胜感激。
干杯

采纳答案by rici

=~succeeds if the string on the left containsa match for the regex on the right. If you want to know if the string matchesthe 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.
  1. 我删除了不必要()从正则表达式,并""[[ ... ]]
  2. bash 手册措辞不佳,因为它说=~如果字符串匹配则成功。