如何在命令行管道中匹配IPv6地址

时间:2012-09-13 00:36:36

标签: regex grep command-line-interface ipv6

如何在stdin中创建一个查找IPv6地址的shell命令?

一种选择是使用:

grep -Po '(?<![[:alnum:]]|[[:alnum:]]:)(?:(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}|(?:[a-f0-9]{1,4}:){1,6}:(?:[a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4})(?![[:alnum:]]:?)'

此RE基于“Regular expression that matches valid IPv6 addresses”的提示,但这不太准确。我可以使用一个更丑陋的正则表达式,但是有更好的方法,一些我不知道的命令吗?

1 个答案:

答案 0 :(得分:2)

由于我找不到使用shell脚本命令的简单方法,我在Python中创建了自己的方法:

#!/usr/bin/env python

# print all occurences of well formed IPv6 addresses in stdin to stdout. The IPv6 addresses should not overlap or be adjacent to eachother. 

import sys
import re

# lookbehinds/aheads to prevent matching e.g. 2a00:cd8:d47b:bcdf:f180:132b:8c49:a382:bcdf:f180
regex = re.compile(r'''
            (?<![a-z0-9])(?<![a-z0-9]:)
            ([a-f0-9]{0,4}::?)([a-f0-9]{1,4}(::?[a-f0-9]{1,4}){0,6})?
            (?!:?[a-z0-9])''', 
        re.I | re.X)

for l in sys.stdin:
    for match in regex.finditer(l):
        match = match.group(0)
        colons = match.count(':')
        dcolons = match.count('::')
        if dcolons == 0 and colons == 7:
            print match
        elif dcolons == 1 and colons <= 7:
            print match