简体   繁体   中英

How to gsub \ in ruby array?

How to remove all \\ elements from the array?

Array of size 6:

data =
[
      " \"\"http://www.web1.com\\\"",
      "\"",
      " \"\"https://www.web2.com\\\"",
      "\"",
      " \"\"http://www.web3.com\\\"",
      "\"",
 ]

desired:

 ["www.web1.com", "www.web2.com", "www.web3.com"]

tried :

 data = 
 => [" \"\"http://www.web1.com\\\"", "\"", " \"\"https://www.web2.com\\\"", "\"", " \"\"http://www.web3.com\\\"", "\""] 
2.0.0-p353 :019 > data.each do |d| 
2.0.0-p353 :020 >     d.gsub!(/\+/,'')
2.0.0-p353 :021?>   end
 => [" \"\"http://www.web1.com\\\"", "\"", " \"\"https://www.web2.com\\\"", "\"", " \"\"http://www.web3.com\\\"", "\""] 
2.0.0-p353 :022 > 

Here is how you can get your desired output:

data.map { |e| e.gsub(/["\s\\\/]|(?:https?:\/\/)/,'') }.reject(&:empty?)

You iterate over data array and substitute element's contents that match regexp with '' . Then you just drop empty strings.

Let me explain the regexp a little: [...] means group of characters, we will match any character from a group; | is or operator; (?:) is non-capuring group, so we must match whole https:// or http:// ; \\s means any whitespace character; \\\\ and \\/ are escaped \\ and / .

This will give you the result you expected.

data.grep(/https?:\/\/([^\\]*)/) {|v| v.match(/https?:\/\/([^\\]*)/)[1] }

But you have to know that \\ is used to escape the special char in the string.

"\\\\" has only one char that is \\ , "\\"" has only one char that is " .

您可以执行以下操作来全部\\

your_string.gsub('\','')
data.grep(/http/){|x|x.delete '\\\" '}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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