如何创建一个 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/