如何在ruby gem中替换system()中的parantheses

时间:2015-05-30 20:26:08

标签: ruby regex

我想在ruby中使用system()。 system()内部的字符串包含parantheses。所以我试过了:

filenamenew = filename.gsub(/ /, '_').gsub(/(/, '|').gsub(/)/, ']')

可悲的是我得到了:

  

/home/sascha/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in require': /home/sascha/ownCloud/RubymineProjects/youtube_dlhelper/lib/youtube_dlhelper/ripper.rb:57: end pattern with unmatched parenthesis: /(/ (SyntaxError) unmatched close parenthesis: /)/ from /home/sascha/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in require'from ./ youtube_dlhelper.rb:24:在''

我能解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

您收到此错误是因为您需要转义正则表达式中的括号,即

"Hello()".gsub(/\(/, ' World')

将返回" Hello World)"

答案 1 :(得分:1)

这里有一些正则表达式来摆脱括号,括号和空格:

/(\(|\)|\s|\[|\])/

"Rednex - Cotton Eye Joe (Official Music Video) [HD] - RednexMusic com.m4a".gsub(/(\(|\)|\s|\[|\])/, "")

输出:

"Rednex-CottonEyeJoeOfficialMusicVideoHD-RednexMusiccom.m4a"

答案 2 :(得分:1)

另一种可读的变体可能是

str = "Rednex - Cotton Eye Joe (Official Music Video) [HD] - RednexMusic com.m4a"

pattern = /[a-zA-Z0-9\-\s\_]/  #=> set the pattern accepted

#=> check each character keep only if they are in the pattern and join them
str.split(//).keep_if{|chr| chr =~ pattern}.join #=> "Rednex - Cotton Eye Joe Official Music Video HD - RednexMusic comm4a"