如何使用正则表达式用括号括起文本? [英] How to surround text with brackets using regex?

查看:34
本文介绍了如何使用正则表达式用括号括起文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图用括号括起通过正则表达式找到的一些文本.例如,将所有 is 替换为 (is) :

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)

推荐答案

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"

这篇关于如何使用正则表达式用括号括起文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆