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

时间:2011-01-11 06:09:42

标签: ruby regex

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

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

我该怎么做? (虽然仍然保持找到的字符串的原始案例)

2 个答案:

答案 0 :(得分:6)

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"

答案 1 :(得分:1)

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

  

\ B [II] [SS] \ B'/ P>

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

为了用括号,圆括号或其他东西包围匹配的模式:

  

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

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

编辑:您可以在此处测试您的正则表达式:ruby regex