【发布时间】:2015-10-25 22:28:35
【问题描述】:
我有以下字符串:
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。
我看到了一些使用“扫描”或“拆分”来保留分隔符(如果它位于字符串之后)的帖子
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
【问题讨论】:
-
\n真的是换行符吗? -
是 \n 是换行符
标签: ruby regex ruby-on-rails-3 ruby-on-rails-4