Remove double quotes from string

前端 未结 4 1291
不思量自难忘°
不思量自难忘° 2021-01-01 19:20

I\'m trying to grab data from a MySQL database and use Ruby to reformat it into a flat text file. Some of my MySQL data contains double quotes like so:

<
相关标签:
4条回答
  • 2021-01-01 19:58

    You could use something like:

    text = 'Matthew "Matt" Perry'
    
    text.tr(%q{"'}, '|') # => "Matthew |Matt| Perry"
    
    text = "Matthew 'Matt' Perry"
    text.tr(%q{"'}, '|') # => "Matthew |Matt| Perry"
    
    0 讨论(0)
  • 2021-01-01 20:07

    This will do it if you don't want to modify s:

    new_s = s.gsub /"/, '|'
    

    If you do want to modify s:

    s.gsub! /"/, '|'
    
    0 讨论(0)
  • 2021-01-01 20:09

    It removes doublequotes. You can see them in IRB or when using p only because string are being showed for you in these cases in nice form, allowing you to see, that they are strings.

    irb> 'Matthew "Matt" Perry'.scan(/'(.+?)'|"(.+?)"|([^ ]+)/).flatten.compact
    => ["Matthew", "Matt", "Perry"]
    

    In real, they already don't have doublequotes.

    irb> puts 'Matthew "Matt" Perry'.scan(/'(.+?)'|"(.+?)"|([^ ]+)/).flatten.compact
    Matthew
    Matt
    Perry
    => nil
    

    And to replace doublequotes with dash, you may use .tr:

    irb> 'Matthew "Matt" Perry'.tr '"','|'
    => "Matthew |Matt| Perry"
    
    0 讨论(0)
  • 2021-01-01 20:13

    Other choices are:

    s.tr! '"', '|'
    s2 = s.tr '"', '|'
    
    0 讨论(0)
提交回复
热议问题