简体   繁体   English

奇怪的 String.split("\\n") 行为

[英]Strange String.split("\n") behavior

I have a .txt text file, containing some lines.. I load the contain using the RequestBuilder object, and split the responseText with words = String.split("\\n");我有一个 .txt 文本文件,其中包含一些行。我使用 RequestBuilder 对象加载包含,并使用 words = String.split("\\n"); 拆分 responseText; but i wonder, why the result is contains the "\\n" part.. For example, my text:但我想知道,为什么结果包含“\\n”部分。例如,我的文字:

abc
def
ghi

the result is,结果是,

words[0] = "abc\n"
words[1] = "def\n"
words[2] = "ghi\n"

Any help is highly appreciated.任何帮助都受到高度赞赏。 Thanks in advance.提前致谢。

Try using string.split("\\\\n+") . 尝试使用string.split("\\\\n+") Or even better - split("[\\\\r\\\\n]+") 甚至更好split("[\\\\r\\\\n]+")

Windows carriage returns ( "\\r\\n" ) shouldn't make a visible difference to your results, nor should you need to escape the regular expression you pass to String.split() . Windows回车符( "\\r\\n" )不会对结果产生明显的影响,也不必转义传递给String.split()的正则表达式。

Here's proof of both the above using str.split("\\n") : http://ideone.com/4PnZi 这是使用str.split("\\n")证明上述两种情况的方法: http : str.split("\\n")

If you do have Windows carriage returns though, you should (although strictly not necessary) use str.split("\\r\\n") : http://ideone.com/XcF3C 如果您确实有Windows回车符,则应该(尽管绝对没有必要)使用str.split("\\r\\n")http : str.split("\\r\\n")

您可能还需要考虑String[] lines = text.split("\\\\\\\\n");

如果split使用正则表达式,则应使用“ \\\\ n”而不是“ \\ n”

Try using string.split("\\\\\\\\n") . 尝试使用string.split("\\\\\\\\n") It works for me. 这个对我有用。

Maybe it's trivial, but the .split method is sensitive to spaces and text breaks.也许这很简单,但是 .split 方法对空格和文本中断很敏感。 If we don't know how the original text is written, we have to consider that this could make some differences (single line, breaks, multilines, etc).如果我们不知道原文是如何写的,我们必须考虑这可能会产生一些差异(单行、中断、多行等)。

Single line text:单行文字:

const inlineText = "Hello world!";
console.log(inlineText.split(' ')) //['Hello', 'world!']

Multi lines text:多行文字:

const multilinesText = `
Hello world!
`
console.log(multilinesText.split(' ')) // ['\nHello', 'world!', '\n']

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

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