bash 正则表达式“不以”开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16578497/
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-09-18 05:26:20  来源:igfitidea点击:

RegEx for "does not begin with"

regexbashshellinequality

提问by dalawh

The following checks if it begins with "End":

以下检查它是否以“End”开头:

if [[ "$line" =~ ^End ]]

I am trying to find out how to match something that does not begin with "02/18/13". I have tried the following:

我试图找出如何匹配不以“02/18/13”开头的内容。我尝试了以下方法:

if [[ "$line" != ^02/18/13 ]]

if [[ "$line" != ^02\/18\/13 ]]

Neither of them seemed to work.

它们似乎都不起作用。

回答by Gordon Davisson

bash doesn't have a "doesn't match regex" operator; you can either negate (!) a test of the "does match regex" operator (=~):

bash 没有“不匹配正则表达式”运算符;您可以否定 ( !) 对“确实匹配正则表达式”运算符 ( =~) 的测试:

if [[ ! "$line" =~ ^02/18/13 ]]

or use the "doesn't match string/glob pattern" operator (!=):

或使用“不匹配字符串/全局模式”运算符 ( !=):

if [[ "$line" != 02/18/13* ]]

Glob patterns are just different enough from regular expressions to be confusing. In this case, the pattern is simple enough that the only difference is that globs are expected to match the entire string, and hence don't need to be anchored (in fact, it needs a wildcard to de-anchor the end of the pattern).

Glob 模式与正则表达式的不同足以令人困惑。在这种情况下,模式很简单,唯一的区别是 glob 应该匹配整个字符串,因此不需要锚定(实际上,它需要一个通配符来取消锚定模式的结尾)。

回答by gillyspy

Why not just "if not" it?

为什么不只是“如果不是”呢?

if ! [[ "$line" =~ ^02/18/13 ]]

回答by Kyle L

Using the if ! will do the trick. Example: Say line="1234" using this test in bash -

使用如果!会做的伎俩。示例:在 bash 中使用此测试说 line="1234" -

if ! echo "$line" |grep -q "^:" > /dev/null; then echo "GOOD line does NOT begin with : "; else echo "BAD - line DOES begin with : "; fi

It will respond with "GOOD line does NOT begin with : "

它将响应“GOOD 行不以:”开头