简体   繁体   English

正则表达式替换:如果没有后跟字母或数字

[英]regex replace : if not followed by letter or number

Okay so I wanted a regex to parse uncontracted(if that's what it is called) ipv6 adresses 好吧所以我想要一个正则表达式解析未收缩(如果这就是所谓的)ipv6地址

Example ipv6 adress: 1050:::600:5:1000:: 示例ipv6地址: 1050:::600:5:1000::

What I want returned: 1050:0000:0000:600:5:1000:0000:0000 我想要的回报: 1050:0000:0000:600:5:1000:0000:0000

My try at this: 我尝试这个:

ip:gsub("%:([^0-9a-zA-Z])", ":0000")

The first problem with this: It replaces the first and second : 第一个问题:它取代了第一个和第二个:

So :: gets replaced with :0000 所以::替换为:0000

Replacing it with :0000: wouldn't work because then it will end with a : . 用以下内容替换它:0000:不起作用,因为它将以:结束。 Also this would note parse the newly added : resulting in: 1050:0000::600:5:1000:0000: 另外这会注意解析新添加的:导致: 1050:0000::600:5:1000:0000:

So what would I need this regex to do? 那么我需要这个正则表达式做什么呢?

Replace every : by :0000 if it isn't followed by a number or letter 如果后面没有数字或字母,则替换每个: by :0000

Main problem: :: gets replaced instead of 1 : 主要问题::被替换而不是1 :

gsub and other functions from Lua's string library use Lua Patterns which are much simpler than regex. Lua的字符串库中的gsub和其他函数使用Lua Patterns ,它比regex简单得多。 Using the pattern more than once will handle the cases where the pattern overlaps the replacement text. 多次使用该模式将处理模式与替换文本重叠的情况。 The pattern only needs to be applied twice since the first time will catch even pairings and the second will catch the odd/new pairings of colons. 该模式只需要应用两次,因为第一次将捕获偶数配对,第二次将捕获奇数/新配对的冒号。 The trailing and leading colons can be handled separately with their own patterns. 尾随和前导冒号可以使用自己的模式单独处理。

ip = "1050:::600:5:1000::"
ip = ip:gsub("^:", "0000:"):gsub(":$", ":0000")
ip = ip:gsub("::", ":0000:"):gsub("::", ":0000:")
print(ip) -- 1050:0000:0000:600:5:1000:0000:0000

There is no single statement pattern to do this but you can use a function to do this for any possible input: 没有单一的语句模式可以执行此操作,但您可以使用函数为任何可能的输入执行此操作:

function fill_ip(s)
  local ans = {}
  for s in (s..':'):gmatch('(%x*):') do
    if s == '' then s = '0000' end
    ans[ #ans+1 ] = s
  end
  return table.concat(ans,':')
end

--examples:
print(fill_ip('1050:::600:5:1000::'))
print(fill_ip(':1050:::600:5:1000:'))
print(fill_ip('1050::::600:5:1000:1'))
print(fill_ip(':::::::'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM