简体   繁体   English

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

[英]How to remove all symbols inside brackets from string using Ruby?

I have a string "Some words, some other words (words in brackets)" 我有一个字符串“有些单词,有些其他单词(括号中的单词)”

How can I completely remove words in brackets with brackets too, to get "Some words, some other words " string as result? 如何完全删除带有括号的括号中的单词,以得到“某些单词,另一些单词”字符串呢?

I'm newbie for regexp but I promise to learn to they works ) 我是regexp的新手,但我保证会学到它们的工作原理)

Thank for help! 谢谢帮忙!

Try this: 尝试这个:

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

Because of the greedyness of the "*" if there is more than on pair of brackets everything within will be deleted: 由于“ *”的贪婪性,如果在方括号中有多个,则将删除其中的所有内容:

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 " 

A more stable solution would be: 一个更稳定的解决方案是:

/\(.*?\)/
ruby-1.9.2-p290 :008 > s.gsub(/\(.*?\)/, '')
=> "Some words, some other words  some text and more "

Leaving the text between groups of brackets intact. 括号之间的文本保持不变。

String#[] : 字符串#[]

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

The regexp means: group everything (.*) before the first open bracket \\( , and the argument 1 means: take the first group. regexp的意思是:将第一个方括号\\(之前的所有内容(.*)分组,参数1意味着:进行第一组。

If you need to match also the closed bracket you can use /(.*)\\(.*\\)/ , but this will return nil if the string does not contain one of the brackets. 如果还需要匹配括号,则可以使用/(.*)\\(.*\\)/ ,但是如果字符串不包含括号之一,则返回nil

/(.*)(\\(.*\\))?/ matches also strings which not contain brackets. /(.*)(\\(.*\\))?/也匹配不包含方括号的字符串。

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

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