我有一个字符串“一些词,一些其他词(括号中的词)”
我怎样才能完全删除括号中的单词,以获得“一些单词,一些其他单词”字符串作为结果?
我是 regexp 的新手,但我保证会学习他们的工作原理)
感谢您的帮助!
试试这个:
# irb
irb(main):001:0> x = "Some words, some other words (words in brackets)"
=> "Some words, some other words (words in brackets)"
irb(main):002:0> x.gsub(/\(.*?\)/, '')
=> "Some words, some other words "
由于“*”的贪婪,如果有超过一对括号,则其中的所有内容都将被删除:
s = "Some words, some other words (words in brackets) some text and more ( text in brackets)"
=> "Some words, some other words (words in brackets) some text and more ( text in brackets)"
ruby-1.9.2-p290 :007 > s.gsub(/\(.*\)/, '')
=> "Some words, some other words "
更稳定的解决方案是:
/\(.*?\)/
ruby-1.9.2-p290 :008 > s.gsub(/\(.*?\)/, '')
=> "Some words, some other words some text and more "
保持括号组之间的文本不变。
>> "Some words, some other words (words in brackets)"[/(.*)\(/, 1]
#=> "Some words, some other words "
正则表达式的意思是:(.*)
将第一个开括号之前的所有内容分组\(
,而参数的1
意思是:取第一组。
如果您还需要匹配可以使用的封闭括号,但如果字符串不包含括号之一,/(.*)\(.*\)/
则会返回。nil
/(.*)(\(.*\))?/
也匹配不包含括号的字符串。