0

我有这个集合(点数可变,这里是 2):

A 
 This is some Text belonging to A
 This also belongs to A
B 
 This should be with B
 same with this
...
...

我希望它最终成为这样的字符串:

A This is some Text belonging to A This also belongs to A
B This should be with B same with this

我的尝试是这样的:

answer.scan(/^([A-Z].+?(?=^[A-Z]))/m).map { |d| d.delete("\n") }.join("\n")

问题是这与最后一组不匹配(您可以假设字符串以最后一组结尾)有什么想法吗?:)

编辑1:修复了一个复制错误并在Rubular中尝试了一个新的正则表达式,哪种方法有效,但仍有一些不必要的匹配?

4

2 回答 2

4
text = <<EOS
A 
 This is some Text belonging to A
 This also belongs to A
B 
 This should be with B
 same with this
 variable line
EOS

text.gsub(/\s?\n\s/, ' ')

# Outputs: 
# A This is some Text belonging to A This also belongs to A
# B This should be with B same with this variable line
于 2012-12-05T10:25:19.587 回答
1
answer = answer
.scan(/^([A-Z].+?(?=^[A-Z]))|(^[A-Z].+?\Z)/m)
.map {|item| item.reject { |i| i.nil? } }
.map { |d| d[0].delete("\n") }
.join("\n")

似乎现在可以工作......虽然可能不是最好的方法

于 2012-12-05T10:50:17.770 回答