开发者

How to surround text with brackets using regex?

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 s开发者_运维知识库till maintaining the original case-ness of the found strings)


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"


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜