【问题标题】:Ruby: replace a multi-line text inside a document with another textRuby:用另一个文本替换文档中的多行文本
【发布时间】:2021-01-13 14:30:53
【问题描述】:

我有以下文件:

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",没有成功。

【问题讨论】:

    标签: ruby string replace newline


    【解决方案1】:

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

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

    /@NiceFunction(.*)@End/m
    

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

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

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

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

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-29
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        相关资源
        最近更新 更多