text = "This [is] a [fill]-in-the-[blank]"
我正在寻找一个正则表达式,让我可以进行一些神奇的操作:
new_text = text.gsub(/[magic happens]/, "")
=> "This [] a []-in-the-[]"
我的代码是Ruby,但我敢打赌这并不重要。
类似这样的代码可以正常工作:
text = "This [is] a [fill]-in-the-[blank]"
text.gsub(/\[.+?\]/, '[]')
#=> "This [] a []-in-the-[]"
text = "This [is] a [fill]-in-the-[blank]"
text.gsub(/(?<=\[).+?(?=\])/, "")
或者
text.gsub(/(?<=\[)[^\]]+?(?=\])/, "")
我使用Rubular来原型化这个,根据你的测试用例->http://rubular.com/r/TgdjOtc4Ru从这里,你可以删除匹配项或类似的内容:
[5] pry(main)> text = "This [is] a [fill]-in-the[blank]"
=> "This [is] a [fill]-in-the[blank]"
[6] pry(main)> text.gsub(/\[(\w+)\]/) { |match| "[]" }
=> "This [] a []-in-the[]"
可能有更好的方法来做到这一点 :-)