문제

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 > 
도움이 되었습니까?

해결책 2

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

다른 팁

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 /.

You can gsub all \ by doing:

your_string.gsub('\','')
data.grep(/http/){|x|x.delete '\\\" '}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top