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

标签 regex grep command-line-interface ipv6

如何创建一个 shell 命令来在其标准输入中查找 IPv6 地址?

一种选择是使用:

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”的想法,但这并不十分准确。我可以使用更丑陋的正则表达式,但是有没有更好的方法,一些我不知道的命令?

最佳答案

由于我找不到使用 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

关于regex - 如何在命令行管道中匹配 IPv6 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12397902/

相关文章:

regex - 在Notepad++中删除最后一个数字之前的字符

python - 使用 grep 比较两个 Python 包列表

node.js - GraphicsMagick + ImageMagick + 拒绝错误 : Command failed:

javascript - 针对 javascript 中的多个正则表达式测试字符串

c# - 用正则表达式分割

python - 正则表达式替换所有除非行尾($ in [] issue)

ubuntu - 在 Ubuntu 上的 grep 中,如何只显示与正则表达式匹配的字符串?

linux - 在 bash 中匹配逗号分隔列表中的单词

azure - 解析来自 Azure CLI 的 json 结果时出错 : launching Azure CLI: exec: "az": executable file not found in %PATH%

c# - 无法从 CLI 读取数据