2

I'm stuck trying to surround some text found via regex with brackets. For example replacing all is with (is) :

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

How can I do this? (While still maintaining the original case-ness of the found strings)

Zabba
  • 64,285
  • 47
  • 179
  • 207

2 Answers2

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"
ephemient
  • 198,619
  • 38
  • 280
  • 391
  • Great, thanks! Can you give me the "name" of what that "\0" is so I can read up about it ? – Zabba Jan 11 '11 at 06:23
  • \1 \2 etc. represent capture groups (e.g. the first set of `()` parens in the regex, the second, etc.) and \0 represents the whole regex match. (Within the regex they're called backreferences, but I'm not sure what they're called once you're outside the regex.) – ephemient Jan 11 '11 at 06:28
  • @Zabba `\0` contain the entire contents of the text matched by the regular expression. – Alex Jan 11 '11 at 06:28
1

For your example, the regex pattern to find matches for "is" is:

\b[iI][Ss]\b

You may also want to use \b, the word boundary

In order to surround the matching pattern with brackets, parentheses, or whatnot:

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

Basically, \0 is the previous match which is to be replaced by itself surrounded by parentheses.

EDIT: You can test your regex here: ruby regex

avendael
  • 2,459
  • 5
  • 26
  • 30