【问题标题】:Ruby split keep the delimiter before the stringRuby split 将分隔符保留在字符串之前
【发布时间】: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


【解决方案1】:
(?<=\\n)\s*(?=%%)

您可以使用lookaroundsspace 上拆分。查看演示。

https://regex101.com/r/fM9lY3/7

【讨论】:

  • \n 和 %% 之间不需要有空格,因为 \n 描绘了一个新行
  • 有趣。让我试试看。
  • 当字符串不是 \n 实际输入时,上述解决方案不起作用。..
【解决方案2】:

你可以这样做

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 中的情况一样,因为尾随空格。

【讨论】:

    【解决方案3】:

    你也可以使用

    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"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 2013-02-01
      • 2014-03-18
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      相关资源
      最近更新 更多