我有以下字符串:
a = '% abc \n %% abcd \n %% efgh\n '
我希望输出
['% abc \n', '%% abcd \n', '%% efgh \n']
如果我有
b = '%% abc \n %% efg \n %% ijk \n]
我希望输出为
['%% abc \n', '%% efg \n', '%% ijk \n']
我使用b.split('%%').collect!{|v| '%%' + v }
,它适用于案例2。
但它不适用于案例1.
我看到一些使用'scan'或'split'来保留分隔符的帖子,如果它在字符串之后
For example : 'a; b; c' becomes ['a;', 'b;' ,'c']
But I want the opposite ['a', ';b', ';c']
\ n和%%之间不需要空格,因为\ n描绘了一个新行。
我做的解决方案是
sel = '% asd \n %% asf sdaf \n %% adsasd asdf asd asf ';
delimiter = '%%';
indexOfPercent = test_string.index("%%")
if(indexOfPercent == 0)
result = (test_string || '').split(delimiter).reject(&:empty?).collect! {|v| delimiter + v}
else
result = (test_string.slice(test_string.index("%%")..-1) || '').split(delimiter).reject(&:empty?).collect! {|v| delimiter + v}
result.unshift(sel[0.. indexOfPercent-1])
end
答案 0 :(得分:1)
答案 1 :(得分:1)
你可以这样做
def splitter(s)
#reject(&:empty) added to handle trailing space in a
s.lines.map{|n| n.lstrip.chomp(' ')}.reject(&:empty?)
end
#double quotes used to keep ruby from changing
# \n to \\n
a = "% abc \n %% abcd \n %% efgh\n "
b = "b = '%% abc \n %% efg \n %% ijk \n"
splitter(a)
#=> ["% abc \n", "%% abcd \n", "%% efgh\n"]
splitter(b)
#=> ["%% abc \n", "%% efg \n", "%% ijk \n"]
默认情况下, String#lines
会在换行符后面对字符串进行分区。 (这将返回Array
。然后我们调用Array#map
并传入每个匹配的字符串。然后,此字符串调用lstrip
以删除前导空格,chomp(' ')
删除尾随空格空格而不删除\n
。然后我们reject
任何空字符串,就像变量a
中的情况一样,因为尾随空格。
答案 2 :(得分:1)
您也可以使用
a.split(/\\n\s?/).collect{|e| "#{e}\\n"}
a.split(/\\n\s?/)
# ["% abc ", "%% abcd ", "%% efgh"]
.collect{|e| "#{e}\\n"}
# will append \n
# ["% abc \\n", "%% abcd \\n", "%% efgh\\n"]