Bash 正则表达式 =~ 运算符

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

Bash regex =~ operator

bashshellunix

提问by user339946

What is the operator =~called? Is it only used to compare the right side against the left side?

运营商=~叫什么?它仅用于比较右侧和左侧吗?

Why are double square brackets required when running a test?

为什么在运行测试时需要双方括号?

ie. [[ $phrase =~ $keyword ]]

IE。 [[ $phrase =~ $keyword ]]

Thank you

谢谢

采纳答案by Carl Norum

  1. What is the operator =~called?

    I'm not sure it has a name. The bash documentationjust calls it the =~operator.

  2. Is it only used to compare the right side against the left side?

    The right side is considered an extended regular expression. If the left side matches, the operator returns 0, and 1otherwise.

  3. Why are double square brackets required when running a test?

    Because =~is an operator of the [[ expression ]]compound command.

  1. 运营商=~叫什么?

    我不确定它有没有名字。在bash的文件只是调用它的=~操作。

  2. 它仅用于比较右侧和左侧吗?

    右侧被认为是扩展的正则表达式。如果左侧匹配,则运算符返回01否则返回。

  3. 为什么在运行测试时需要双方括号?

    因为=~[[ expression ]]复合命令的运算符。

回答by Wirawan Purwanto

The =~operator is a regular expression match operator. This operator is inspired by Perl's use of the same operator for regular expression matching.

=~运营商正则表达式匹配运算符。这个运算符的灵感来自 Perl 使用相同的运算符进行正则表达式匹配。

The [[ ]]is treated specially by bash; consider that an augmented version of [ ]construct:

[[ ]]是通过bash的特殊处理; 考虑[ ]构造的增强版本:

  • [ ]is actually a shell built-in command, which, can actually be implemented as an external command. Look at your /usr/bin, there is most likely a program called "[" there! Strictly speaking, [ ]is not part of bash syntax.

  • [[ ]]is a shell keyword, which means it is part of shell syntax. Inside this construct, some reserved characters change meaning. For example, ( )means parenthesis like other programming language (not launching a subshell to execute what's inside the paretheses). Another example is that <and >means less than and greater than, not shell redirection. This allow more "natural" appearance of logical expressions, but it can be confusing for novice bash programmers.

  • [ ]实际上是一个shell内置命令,它实际上可以作为一个外部命令来实现。看看你的/usr/bin,那里很可能有一个名为“[”的程序!严格来说,[ ]不是 bash 语法的一部分。

  • [[ ]]是一个 shell 关键字,这意味着它是 shell 语法的一部分。在这个结构中,一些保留字符改变了含义。例如,( )表示括号与其他编程语言一样(不启动子shell 来执行括号内的内容)。另一个例子是<and>表示小于和大于,而不是shell重定向。这允许逻辑表达式更“自然”的外观,但它可能会让新手 bash 程序员感到困惑。

Wirawan

威拉万