簡體   English   中英

Ruby中的正則表達式字符串解析

[英]Regex string parsing in Ruby

我有這個設置(點數可變,這里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")

問題在於這與最后一組不匹配(您可以假定字符串以最后一組結尾)有什么想法嗎? :)

edit1:修復了coyping錯誤,並在Rubular中嘗試了新的正則表達式,這是一種什么樣的工作,但是仍然有一些不必要的匹配項?

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

似乎暫時起作用...雖然可能不是最好的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM