如何使用正则表达式括号括起文本?

我试图用带括号的正则表达式包围一些文本。 例如,替换all is (is)

 Input is : This is a long sentence that IS written. Desired output: This (is) a long sentence that (IS) written. 

我怎样才能做到这一点? (虽然仍然保持找到的字符串的原始案例)

 irb(main):001:0> s = 'This is a long sentence that IS written.' => "This is a long sentence that IS written." irb(main):002:0> s.gsub(/\bis\b/i, '(\0)') => "This (is) a long sentence that (IS) written" irb(main):003:0> s => "This is a long sentence that IS written" irb(main):004:0> s.gsub!(/\bis\b/i, '(\0)') => "This (is) a long sentence that (IS) written" irb(main):005:0> s => "This (is) a long sentence that (IS) written" 

对于您的示例,查找“is”匹配的正则表达式模式是:

\ B [II] [SS] \ b

您可能还想使用\ b,单词边界

为了用括号,括号或诸如此类的东西包围匹配的模式:

gsub(/ \ b [iI] [Ss] \ b /,“(\ 0)”)

基本上,\ 0是前一个匹配,由括号括起来自己替换。

编辑:你可以在这里测试你的正则表达式: ruby正则表达式