Bash脚本中的正则表达式 [英] Regular Expression in Bash Script

查看:115
本文介绍了Bash脚本中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello awesome community,



当我们使用正则表达式时,我是一个完整的意思。我已经推迟了学习,现在我的懒惰已经赶上了我。



我要做的是什么:

检查一个字符串是否符合以下格式:

  10_06_13 

ie。今天的日期或类似的日期与2digits_2digits_2digits



我做了什么:

 正则表达式='([0-9] [0-9] [_] [0-9] [0-9] [_] [0-9] [0-9] )'
如果[[$ incoming_string=〜$ regex]]
然后
#在这里做真棒的东西
fi
/ pre>

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



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

干杯

解决方案

=〜成功,如果左侧中的字符串包含正确的正则表达式匹配。如果您想知道字符串匹配正则表达式,则需要锚定两边的正则表达式,如下所示:

 正则表达式= '^ [0-9] [0-9] [_] [0-9] [0-9] [_] [0-9] [0-9] $' 
如果[[$ incoming_string =〜$ regex]]
然后
#在这里做真棒的东西
fi

^ 仅在字符串的开头成功,而 $ 仅在结束时成功。



注意:


  1. 我删除来自 [...]的正则表达式中不必要的() ]

  2. bash手册的措辞不好,因为它表示 c> =〜成功,如果字符串火柴。


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"

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.

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

解决方案

=~ 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.

这篇关于Bash脚本中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆