【问题标题】:How to replace parantheses in system() inside a ruby gem如何在红宝石宝石中替换 system() 中的括号
【发布时间】:2015-08-13 14:03:35
【问题描述】:

我想在 ruby​​ 中使用 system()。 system() 中的字符串内容括号。所以我尝试了:

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:inrequire' 来自 ./youtube_dlhelper。 rb:24:in `'

我可以解决这个问题吗?

【问题讨论】:

  • 你得到的文件名是什么,你希望它最终看起来像什么?另外你是错误的,你的代码似乎没有排队......
  • 在这种情况下,文件名是:Rednex - Cotton Eye Joe (Official Music Video) [HD] - RednexMusic com.m4a
  • 你希望它最终是什么样子的?
  • 我想试试:system("ffmpeg -y -i #{filenamein} -acodec vorbis -vn -ac 2 -aq 60 -strict -2 #{filenamenew}.ogg") . filenamein 是发布的字符串。文件名是 filenamenew = filename.gsub(/ /, '_')。所以空白正在消失。
  • 不完全回答您的问题,但 string 有一个 shellescape 方法可以转义字符串,以便安全地传递给 shell

标签: ruby regex


【解决方案1】:

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

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

将返回“Hello World)”

【讨论】:

    【解决方案2】:

    另一个可读的变化可能是

    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"
    

    【讨论】:

      【解决方案3】:

      这里有一些正则表达式可以去掉括号、括号和空格:

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

      输出:

      "Rednex-CottonEyeJoeOfficialMusicVideoHD-RednexMusiccom.m4a"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2019-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-06
        相关资源
        最近更新 更多