gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:25:09 26 4
gpt4 key购买 nike

我一直试图用括号将通过正则表达式找到的一些文本括起来。例如,将所有 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"

关于ruby - 如何使用正则表达式用方括号括起文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4654723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com