Ruby: 用另一个文本替换文档中的多行文本

Ruby: replace a multi-line text inside a document with another text

我有以下文件:

Some code...
Some more code...

@NiceFunction
    Function content
    More function content
@End

Even more code...

现在我使用 Ruby 将其读入字符串,并想用不同的东西替换 @NiceFunction@End 之间的所有内容。

我试过 string.gsub! /@NiceFunction(.*)@End/, "some other function content" 但这似乎不适用于换行符。

我也试过string.gsub! /@NiceFunction([.\n]*)@End/, "some other function content",但没有成功。

您可以尝试 rubular 来测试正则表达式。目前你需要 'm' 修改器,我认为

string.gsub! /@NiceFunction(.*)@End/m, "some other function content"

正则表达式,在ruby中,默认关闭多行模式匹配。这意味着通配符 . 字符不匹配换行符。

您可以 enable this 使用 /m 修饰符:

/@NiceFunction(.*)@End/m

你的这个尝试似乎也很合理:

/@NiceFunction([.\n]*)@End/

...但不幸的是 当在字符集内时. 失去了它的特殊含义 - 所以这个模式实际上只是在寻找两个字符的重复 ".""\n",并且不会匹配任何其他内容。

但是,您可以采用类似的方法来匹配“任何字符,包括换行符”,而无需启用多行模式。你可以这样做:

/@NiceFunction([\s\S]*)@End/

...也就是说匹配“任何空白或非空白”。换句话说,绝对是任何东西。

上述方法在技术上适用于任何一对否定组 - 例如[\d\D],或[\w\W],或[\h\H],...但出于此目的使用[\s\S]在某种程度上是一种非官方标准。