字符串拆分不返回空结果 [英] String split not returning empty results

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

问题描述

我正在尝试使用

"value1:value2::value3".split(":");

问题是我希望它包含空白结果。

Problem is that I want it to include the blank results.

它返回: [value1,value2,value3]

它应该是: [value1,value2,value3]

有没有人知道正则表达式来解决这个问题?

Does anyone know the regexp to fix this?

好的,我找到了问题原因。我实际上正在阅读一个文本文件,它包含这一行:

Ok I found cause of problem. I'm actually reading a text file and it contains this line:

123:;~\&:ST02:M:test:M:4540145::type;12:51253:D:2.2:567766::AL:::::::2.2b

当我处理这一行读取文本文件时,它会产生上面提到的错误结果,在这种情况下它不包括任何空结果::::::。

When I process this line reading the text file it produces the erroneous result mentioned above, which is it doesn't include any empty results in cases like this: :::::.

但是当我在测试程序中使用上面的行时,它不会编译,我得到一个无效的转义序列。我认为这是因为\&。

But when I use the above line in a test program it doesn't compile and I get a "invalid escape sequence". I think its because of the "\&".

使用正则表达式是否有解决此问题的方法?

Is there a workaround to this problem by using a regular expression?

推荐答案

split 确实在结果中包含空匹配,看看这里的文档 。但是,默认情况下,将丢弃尾随空字符串(数组末尾的字符串)。如果你想包括这些,请尝试 split(:, - 1)

split does include empty matches in the result, have a look at the docs here. However, by default, trailing empty strings (those at the end of the array) are discarded. If you want to include these as well, try split(":", -1).

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

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