regex - 如何使用 bash(3.2.25) 的一个额外的二元运算符 :=~

标签 regex linux bash

看了rhel5.5的bash(3.2.25)的资料,对"=~"怎么用感到困惑

# match the IP, and return true
[kevin@server1 shell]# [[ 192.168.1.1 =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] && echo ok || echo fail
ok

# add double qoute
# return false, en ... I know.
[kevin@server1 shell]# [[ 192.168 =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] && echo ok || echo fail
fail

# remove double qoute
# return ture ? Why ?
[kevin@server1 shell]# [[ 192.168 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && echo ok || echo fail
ok 

那么,我应该把字符串放在运算符右边吗?
为什么第二个命令返回true,按理说应该返回false!

信息如下:

An additional binary operator, =~', is available, with the same precedence as==' and !='. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell optionnocasematch' (see the description of shopt' in *Note Bash Builtins::) is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variableBASH_REMATCH'. The element of BASH_REMATCH' with index 0 is the portion of the string matching the entire regular expression. The element ofBASH_REMATCH' with index N is the portion of the string matching the Nth parenthesized subexpression.

最佳答案

推荐的、最广泛兼容的处理正则表达式模式的方法是用单引号单独声明它们:

$ re='^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
$ [[ 192.168.1.1 =~ $re ]] && echo ok || echo fail 
ok
$ [[ 192.168 =~ $re ]] && echo ok || echo fail 
fail

可以在 Greg's Wiki 上找到关于 bash 版本行为差异的一些讨论。 - 关键信息是使用不带引号的变量是最好的方法。

关于regex - 如何使用 bash(3.2.25) 的一个额外的二元运算符 :=~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730879/

相关文章:

c# - 使用正则表达式匹配多个模式

Jquery验证引擎: Expression for Disallowing Only Certain Characters

linux - 由于 v2.11 弃用而更改 ansible 循环

json - 在不丢弃文档其余部分的情况下更改 JSON 列表中与条件匹配的条目

regex - 带反引号的 grep 正则表达式匹配所有行

python - 使用 BS4 从网页中提取多个不带 'a' 或 'href' 标签的 URL

linux - 在 Linux 上使用 libhid 确定 USB HID 设备的 HID 路径

c++ - 如何检查我的输入文件是否已更新?

bash - 在 Windows 上的 Ubuntu 上的 Bash 中复制粘贴

php - preg_match 包含键值模式的字符串