正则表达式以匹配IP地址 [英] Regex to match IP addresses
问题描述
我试图通过正则表达式匹配在 traceroute
输出中找到的IP地址.我不是要验证它们,因为它足以假定 traceroute
是有效的(即不会输出类似 999.999.999.999
的东西.我正在尝试以下正则表达式:
I am trying to match IP addresses found in the output of traceroute
by means of a regex. I'm not trying to validate them because it's safe enough to assume traceroute
is valid (i.e. is not outputting something like 999.999.999.999
. I'm trying the following regex:
([0-9]{1,3}.?){4}
我正在 regex101 中对其进行测试,它确实可以验证IP地址.但是,当我尝试
I'm testing it in regex101 and it does validate an IP address. However, when I try
echo '192.168.1.1 foobar' | grep '([0-9]{1,3}.?){4}'
我什么也没得到.我想念什么?
I get nothing. What am I missing?
推荐答案
您使用了POSIX ERE模式,但没有通过 -E
选项使 grep
使用POSIX ERE风味.因此, grep
使用POSIX BRE代替,在这里您需要转义 {n,m}
量词和(...)
使其成为解析为特殊的正则表达式运算符.
You used a POSIX ERE pattern, but did not pass -E
option to have grep
use the POSIX ERE flavor. Thus, grep
used POSIX BRE instead, where you need to escape {n,m}
quantifier and (...)
to make them be parsed as special regex operators.
请注意,您需要转义.
,以便它只能与文字点匹配.
Note you need to escape a .
so that it could only match a literal dot.
要使您的模式与 grep
一起使用,您可以使用以下方式:
To make your pattern work with grep
the way you wanted you could use:
grep -E '([0-9]{1,3}\.?){4}' # POSIX ERE
grep '\([0-9]\{1,3\}\.\?\)\{4\}' # POSIX BRE version of the same regex
参见在线演示.
但是,由于.
是可选的,因此此正则表达式还将匹配多个数字的字符串.
However, this regex will also match a string of several digits because the .
is optional.
您可以通过展开模式来解决它
You may solve it by unrolling the pattern as
grep -E '[0-9]{1,3}(\.[0-9]{1,3}){3}' # POSIX ERE
grep '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' # POSIX BRE
请参见另一个演示.
基本上,它匹配:
-
[0-9] {1,3}
-出现1至3次任何ASCII数字 -
(\.[0-9] {1,3}){3}
-3次出现:-
\.
-文字.
-
[0-9] {1,3}
-任意ASCII数字出现1至3次
[0-9]{1,3}
- 1 to 3 occurrences of any ASCII digit(\.[0-9]{1,3}){3}
- 3 occurrences of:\.
- a literal.
[0-9]{1,3}
- 1 to 3 occurrences of any ASCII digit
为确保仅匹配有效的IP,您可能需要使用更精确的IP匹配正则表达式:
To make sure you only match valid IPs, you might want to use a more precise IP matching regex:
grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\b' # POSIX ERE
请参见此在线演示.
您可以进一步调整单词边界(可以是
\<
/\>
或\ b
),等等.You may further tweak it with word boundaries (can be
\<
/\>
or\b
), etc.要提取IP ,请对
grep
使用-o
选项:grep -oE'ERE_pattern'文件
/grep -o'BRE_pattern'文件
.To extract the IPs use
-o
option withgrep
:grep -oE 'ERE_pattern' file
/grep -o 'BRE_pattern' file
.这篇关于正则表达式以匹配IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-