简体   繁体   English

使用regex + gsub从字符串中删除方括号内的文本

[英]Remove just the text within square brackets from a string with regex + gsub

text = "This [is] a [fill]-in-the-[blank]"

I'm looking for the regular expression to do some magic for me: 我正在寻找正则表达式为我做一些魔术:

new_text = text.gsub(/[magic happens]/, "")

=> "This [] a []-in-the-[]"

My code is Ruby, but I'll bet that doesn't matter much. 我的代码是Ruby,但我敢打赌,这并不重要。

Something like this would work: 像这样的东西会起作用:

text = "This [is] a [fill]-in-the-[blank]"
text.gsub(/\[.+?\]/, '[]')
#=> "This [] a []-in-the-[]"
text = "This [is] a [fill]-in-the-[blank]"

text.gsub(/(?<=\[).+?(?=\])/, "")

or 要么

text.gsub(/(?<=\[)[^\]]+?(?=\])/, "")

I used Rubular to prototype this, given your test case -> http://rubular.com/r/TgdjOtc4Ru From here, you can remove the matches or something similar: 考虑到你的测试用例,我使用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[]"

There is probably a prettier way to do that :-) 可能有一个更漂亮的方法:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM