我想在 Ruby 中对 Unicode 字符串进行切片。 切片应保持不可见字符完整。
这是输入的示例:
Foo\r\n
\r\n
\r\n
Bär 1.234 Foo test\r\n
blub
应该变成:
Array=["Foo\r\n\r\n\r\n","Bär","1.234,"Foo","test\r\n","blub"]
基本上我想标记字符串并保持格式不变。
当我做类似的事情时:
String.split(/ /)
我最终得到的结果是这样的:
Array=["Foo\r\n\r\n\r\nBär","1.234","Foo"]
并且,类似:
String.split(/\W/)
取消格式设置。
最佳答案
第一部分不要使用 split
,而是使用 scan
:
text = "Foo\r\n\r\n\r\nBär 1.234 Foo test\r\nblub"
text.scan(/^.+[\r\n]*/)
=> ["Foo\r\n\r\n\r\n", "Bär 1.234 Foo test\r\n", "blub"]
然后有条件地应用您的分割,如下所示:
text.scan(/^.+[\r\n]*/).map{ |s| s[' '] ? s.split(/ /) : s }.flatten
=> ["Foo\r\n\r\n\r\n", "Bär", "1.234", "Foo", "test\r\n", "blub"]
或者:
text.scan(/^.+[\r\n]*/).flat_map{ |s| s[' '] ? s.split(/ /) : s }
=> ["Foo\r\n\r\n\r\n", "Bär", "1.234", "Foo", "test\r\n", "blub"]
关于ruby - 如何将字符串拆分为数组,并保持换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13627484/