ColdFusion正则表达式正确格式化ipv6地址

时间:2017-04-04 03:24:37

标签: coldfusion coldfusion-11

虽然在SO上有这样的例子,但其中很多都涉及删除前导零或组合" 0:0:"序列成" ::"。我见过的大多数例子都是针对其他语言的。

这是我压缩/格式化ipv6地址的功能:

<cffunction name="formatIPv6" returntype="string" output="yes" access="public" hint="returns a compressed ipv6 address">
    <cfargument name="vcIPv6" type="string" required="yes" hint="IPv6 address">

    <!--- inside reReplace removes leading zeros, outside reReplace removes repeating ":" and "0:" --->
    <cfreturn reReplace(reReplace(LCase(arguments.vcIPv6), "(:|^)(0{0,3})([1-9a-f]*)", "\1\3", "all"), "(^|:)[0|:]+:", "::", "all")>
</cffunction>

运行带有示例ipv6地址的函数将返回预期结果:

formatIPv6(vcIPv6 = "0:0:0:0:0:0:0:1") = ::1 (expected value = ::1)
formatIPv6(vcIPv6 = "0000:0000:0000:0000:0000:0000:0000:0001") = ::1 (expected value = ::1)
formatIPv6(vcIPv6 = "1000:0:0:0:8:800:000c:417a") = 1000::8:800:c:417a (expected value = 1000::8:800:c:417a)
formatIPv6(vcIPv6 = "1080:0:0:0:8:800:200C:417A") = 1080::8:800:200c:417a (expected value = 1080::8:800:200c:417a)
formatIPv6(vcIPv6 = "2001:db8:a0b:12f0:0:0:0:1") = 2001:db8:a0b:12f0::1 (expected value = 2001:db8:a0b:12f0::1)
formatIPv6(vcIPv6 = "fe80:0:0:0:204:61ff:fe9d:f156") = fe80::204:61ff:fe9d:f156 (expected value = fe80::204:61ff:fe9d:f156)

我的问题是,两个reReplace()函数可以替换为单个reReplace()吗?

如果有更好的方法可以做到这一点,我可以接受建议。

0 个答案:

没有答案