拆分开始和结束的空字符串 [英] Empty strings at the beginning and end of split

查看:57
本文介绍了拆分开始和结束的空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Ruby 中的拆分问题

在 Ruby 中,当我使用与字符串开头匹配的分隔符拆分字符串时,它会在数组的初始位置给出一个空字符串:

In Ruby, when I split a string with a delimiter that matches the beginning of the string, it gives an empty string in the initial position of the array:

"abc".split(/a/) # => ["", "bc"]

但是当我使用与字符串末尾匹配的分隔符执行类似操作时,它不会给出空字符串:

but when I do a similar thing with a delimiter that matches the end of the string, it does not give an empty string:

"abc".split(/c/) # => ["ab"]

这对我来说似乎不一致.这样的规范有什么理由吗?

This looks inconsistent to me. Is there any rationale for such specification?

编辑如果它要与 Perl 的规范兼容,就像在 muu 中要简短的回答一样,那么问题仍然是相同的:为什么在 Perl 中会这样?也正是因为这个原因,现在它也变成了一个关于 Perl 的问题.

Edit If it is to be compatible with Perl's specification as in muu is to short's answer, then the question remains the same: Why is it like that in Perl? And for this reason, now it also becomes a question about Perl.

推荐答案

看了 AWK 的规范后 mu 太短,我开始觉得 AWK 中 split 的初衷是提取子串对应于字段,每个字段都以标点符号结束,如 .,分隔符被认为是字段结束字符".目的不是将字符串对称地拆分为每个分隔符位置的左侧和右侧,而是终止位于分隔符位置左侧的子串.在这个概念下,在分隔符的左边总是有一些字符串(即使它是空的)是有意义的,但不一定在分隔符的右边.这可能是通过 Perl 继承到 Ruby 的.

After reading AWK's specification following mu is too short, I came to feel that the original intention for split in AWK was to extract substrings that correspond to fields, each of which is terminated by a punctuation mark like ,, ., and the separator was considered something like an "end of field character". The intention was not splitting a string symmetrically into the left and the right side of each separator position, but was terminating a substring on the left side of a separator position. Under this conception, it makes sense to always have some string (even if it is empty) on the left of the separator, but not necessarily on the right side of the separator. This may have been inherited to Ruby via Perl.

这篇关于拆分开始和结束的空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆