如何删除以'a'开头到下一个'b'的子字符串?

时间:2019-03-05 00:25:05

标签: ruby string

我有一个字符串:

a = "select * from ABC -- where  A = B \n And D = C \n -- And  X = Y \n And J = I;"

我想删除所有以"--"开头的子字符串,直到下一个"\n"。因此,在编辑完上述字符串之后,a将是:

a = "select * from ABC  And D = C \n  And J = I;"

1 个答案:

答案 0 :(得分:4)

使用String#gsub!

a = "select * from ABC -- where A = B \n And D = C \n -- And X = Y \n And J = I;"
a.gsub(/--.*\n/, "") #=> "select * from ABC  And D = C \n  And J = I;"

可能因为换行符。

更一般的方式

例如,您需要删除以"foo"开始并以"bar"结尾的子字符串。

a = "aaafoobb\nbbarcccfoodd\tdbareee"
a.gsub(/foo(.*?)bar/m, "") #=> "aaaccceee"