[英]How do I get Ruby's String Split Method to Include Newlines in the Output?
這里有這段代碼:
thing = "Stuff.\nHello!"
result = thing.split(" ")
# ^Is equal to ["Stuff.", "Hello!"] despite the delimiter being a single space instead of a newline
我該怎么做才能包含換行符,使結果 var 等於 ["Stuff.\n", "Hello?"] 呢?
我正在使用 Ruby 1.9.2。 對於那些好奇的人,為了用換行符替換換行符標簽的換行算法,我需要知道這一點。
您可以使用帶有正向后視斷言的正則表達式:
thing = "Stuff.\nHello!"
thing.split(/(?<=\s)/)
#=> ["Stuff.\n", "Hello!"]
正向后視斷言(?<=pat)
確保前面的字符與pat
匹配,但不在匹配的文本中包含這些字符。
可以簡單地使用String#lines 。
"Stuff.\nHello!".lines #=> ["Stuff.\n", "Hello!"]
"Stuff.\nHello!\n".lines #=> ["Stuff.\n", "Hello!\n"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.