如何使用Ruby从字符串中删除括号内的所有符号?

时间:2012-11-14 15:55:48

标签: ruby regex string

我有一个字符串“有些单词,其他一些单词(括号中的单词)”

如何用括号括起括号中的单词,以获得“某些单词,其他单词”字符串作为结果?

我是regexp的新手,但我保证会学习他们的作品)

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

试试这个:

# 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 "

答案 1 :(得分:2)

由于“*”的贪婪,如果超过一对括号,其中的所有内容都将被删除:

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 "

保留括号组之间的文本。

答案 2 :(得分:0)

String#[]

>>  "Some words, some other words (words in brackets)"[/(.*)\(/, 1] 
    #=> "Some words, some other words "

正则表达式意味着:在第一个开括号(.*)之前将所有内容\(分组,参数1表示:取第一个组。

如果您还需要匹配闭括号,可以使用/(.*)\(.*\)/,但如果字符串不包含其中一个括号,则会返回nil

/(.*)(\(.*\))?/也匹配不包含括号的字符串。