perl:如何分割?
我有一个字符串 aa:bb::cc:yy:zz
,需要以这样的方式进行拆分,以便我有一个包含 aa:bb::cc
的数组, yy
,zz
。即我想从最后创建两个子字符串,以 :
作为分隔符,并保留为数组的元素。实现这一目标的最佳方法是什么?
例如:
aa:bb::cc:yy:zz --> ['aa:bb::cc','yy','zz']
dd:ff:gg:dd:ee:ff:fg --> ['dd:ff:gg:dd:ee','ff','gg']
我将 IP 地址:端口:协议作为密钥存储在文件中,并用“:”拆分以获取 IP、端口、协议,当 IP 地址限制为 Ipv4 时,一切正常。现在我想将其移植到Ipv6,在这种情况下IP地址包含“:”,所以我无法通过用“:”分割来获得正确的IP地址。
I have a string aa:bb::cc:yy:zz
which needs to be split in such a way that I have an array with aa:bb::cc
, yy
, zz
. i.e. I want to create two substrings from last with :
as delimiter and remaining as a element of an array. What's the best way to achieve this?
ex:
aa:bb::cc:yy:zz --> ['aa:bb::cc','yy','zz']
dd:ff:gg:dd:ee:ff:fg --> ['dd:ff:gg:dd:ee','ff','gg']
I store IP address:port:protocol as a key in a file , and splitting wiht ":" to get IP,port,proto back and things were working fine when IP address is limited to Ipv4. Now I want to make it ported to Ipv6 in which case IP address contains ":" so I can't get proper IP address by splitting with ":".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
怎么样:
输出:
How about:
output:
当 $string 包含 2 个或更少对时,此代码将纠正处理情况:
This code will correct handle situations when $string contains 2 or less pairs:
我会做一个过于激进的 split 然后进行连接。我认为当您不使用复杂的正则表达式进行分割时,结果更具可读性。所以:
给你:
在开始像这样索引它之前,你必须对 @split_string 进行一些数组边界检查。
I'd do an overly aggressive split followed by a join. I think the result is much more readable when you're not using a complicated regex for the split. So:
Gives you:
You'd have to do some array bounds checking on
@split_string
before you start indexing it like that.更新:您没有提到这是为了解析 IP 地址。如果是,您最好尝试在 CPAN 上查找模块
Update: You did not mention this was meant to parse IP addresses. If it is, you would probably be better off trying to find a module on CPAN