我希望我的split
方法保留换行符而不是删除它们。例如,receipt
文本就是:
receipt = "rpples 1.29\nperrs 1.69\nrsprrrgus 2.19\ngrhpes 1.85\nlettuce 6.87\nstrrwberries 2.79\nbroccoli 1.66"
我想要receipt.split(" ")
,目前返回:
"rpples", "1.29", "perrs", "1.69", "rsprrrgus", "2.19", "grhpes", "1.85", "lettuce", "6.87", "strrwberries", "2.79", "broccoli", "1.66"
返回:
"rpples", "1.29", "\n", "perrs", "1.69", "\n", "rsprrrgus", "2.19", "\n","grhpes", "1.85", "\n", "lettuce", "6.87", "\n", "strrwberries", "2.79", "\n", "broccoli", "1.66"
所以当我在最后使用join
方法(在中间运行另一个方法来纠正所有拼写错误之后)时,最终文本将是:
"rpples 1.29\nperrs 1.69\nrsprrrgus 2.19 ..."
而不是:
"rpples 1.29 perrs 1.69 rsprrrgus 2.19 grhpes 1.85 lettuce 6.87 strrwberries 2.79 broccoli 1.66"
没有"\n"
个字符。在使用split
方法时,请告诉我如何保留换行格式。
答案 0 :(得分:1)
receipt.split(/ |(?<=\n)|(?=\n)/)
分隔空格,换行前或换行后。
答案 1 :(得分:1)
除了Amadan's answer之外,您还可以使用捕获组在结果中包含分隔符(或其中一个分隔符):
receipt.split(/ |(\n)/)
#=> ["rpples", "1.29", "\n", "perrs", "1.69", "\n", ...]
这将按空格(不捕获它)和换行(捕获它)分割。