简体   繁体   English

如何让 Ruby 的字符串拆分方法在 Output 中包含换行符?

[英]How do I get Ruby's String Split Method to Include Newlines in the Output?

There's this code right here:这里有这段代码:

thing = "Stuff.\nHello!"
result = thing.split(" ")
# ^Is equal to ["Stuff.", "Hello!"] despite the delimiter being a single space instead of a newline

How do I make it so that the newline is included, making the result var equal to ["Stuff.\n", "Hello?"] instead?我该怎么做才能包含换行符,使结果 var 等于 ["Stuff.\n", "Hello?"] 呢?

I'm using Ruby 1.9.2.我正在使用 Ruby 1.9.2。 For those who are curious, I need to know this for the sake of a word-wrapping algorithm that replaces line-break tags with newlines.对于那些好奇的人,为了用换行符替换换行符标签的换行算法,我需要知道这一点。

You can use a regexp with a positive look-behind assertion :您可以使用带有正向后视断言的正则表达式:

thing = "Stuff.\nHello!"
thing.split(/(?<=\s)/)
#=> ["Stuff.\n", "Hello!"]

The positive look-behind assertion (?<=pat) ensures that the preceding characters match pat , but doesn't include those characters in the matched text.正向后视断言(?<=pat)确保前面的字符与pat匹配,但不在匹配的文本中包含这些字符。

One could simply use String#lines .可以简单地使用String#lines

"Stuff.\nHello!".lines    #=> ["Stuff.\n", "Hello!"]
"Stuff.\nHello!\n".lines  #=> ["Stuff.\n", "Hello!\n"]

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

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