inet addr的正则表达式失败 [英] Regex for inet addr failed
问题描述
在Ubuntu 16.04中,我运行了 ifconfig
,并在 inet addr中查看了我的外部IP:MY_IP
。
In Ubuntu 16.04 I ran ifconfig
and saw my external ip as in inet addr:MY_IP
.
我试图通过以下方式将其挖到变量中:
I tried to "dug" it right into a variable in these ways:
ipa=$(ifconfig | grep "inet addr:\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
和:
ipa=$(ifconfig | grep "inet addr:\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.")
这些方法有效:
ipa=$(ifconfig | grep -Po 'inet addr:\K[^\s]+' | grep -v '^127')
和
ipa=$(ifconfig | grep -A 1 eth0 | grep -Po "inet addr:(\d{1,3}\.){3}\d{1,3}" | cut -f2 -d:)
但我想请知道,在我的前两次尝试中我错过了什么。
But I would like to know, please, what I've missed in my first 2 tryings.
是否有一种方法来使用一个 grep
有4个组(类似于前2个的概念),确实可以在POSIX BRE中使用吗?
Is there a way to use one grep
with 4 groups (similar to the concept of the first 2) that will indeed work in POSIX BRE?
推荐答案
您可以使用旧式 \<
替换 \b
虽然它似乎不是POSIX。
You can replace \b
with the old-style \<
though it doesn't seem to be POSIX.
另请注意,交替(a | b)
是 grep -E
功能。在POSIX grep中,你可以反斜杠这些结构(很奇怪),但我只需要使用 grep -E
。
Notice also that alternation (a|b)
is a grep -E
feature. In POSIX grep, you can backslash those constructs (weirdly) but I'd just go with grep -E
.
ipa=$(ifconfig | grep -E "inet addr:\<(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.")
没有但是,在那里需要一个单词边界;你已经知道左边的字符是冒号,右边的字符是数字。
There is no need for a word boundary there, though; you already know the character to the left is a colon and the one to the right is a digit.
这篇关于inet addr的正则表达式失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!