我对如何使用" =〜"感到困惑。当我在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!
以下是信息所说的内容:
另一个二元运算符
=~', is available, with the same precedence as
=='和!='. 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 option
nocasematch' (参见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 variable
BASH_REMATCH'的描述。BASH_REMATCH' with index 0 is the portion of the string matching the entire regular expression. The element of
BASH_REMATCH'的索引为N的元素是 匹配第N个带括号的子表达式的字符串部分。
答案 0 :(得分:1)
处理正则表达式模式的推荐的,最广泛兼容的方法是单引号声明它们:
$ 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版本行为差异的一些讨论 - 带回家的消息是使用不带引号的变量是最好的方法。
答案 1 :(得分:0)
与运算符本身无关,但是,正则表达式不会将匹配的IP地址的每个字节限制在0-255之间。该正则表达式将接受IP,例如:999.999.999.999。
请考虑使用以下内容:
^(([01] \ d \ d |?2 [0-4] \ d | 25 [0-5])\){3}([01] \ d \ d |?2 [0-4] \ d | 25 [0-5])$
这将匹配0.0.0.0和255.255.255.255。我在java中使用这是正则表达式但我相信语法是相同的。如果没有,请告诉我们。