Warm tip: This article is reproduced from serverfault.com, please click

Find youtube url in json file with ruby

发布于 2020-12-02 11:49:53

For testing purpose my json file (test.json) consists of only the string I want to find:

"https://www.youtube.com/watch?v=hBIZF3sDFTI"

Somehow I cannot find the string in file with this ruby code:

if not File.foreach("test.json").grep(/https://www.youtube.com/watch?v=hBIZF3sDFTI/).any?

  puts("string not in file")
end

Output: "string not in file"

But the string is in the file.

Searching for other strings works fine, so it must be a problem with this particular string.

Any help is much appreciated!

Questioner
Bisaflam9191
Viewed
0
Todd A. Jacobs 2020-12-02 22:26:16

Problems

Your regex pattern isn't valid, because it's got too many forward slashes in it. Specifically:

/https://www.youtube.com/watch?v=hBIZF3sDFTI/

is not a valid regular expression. Your String is also not a valid a JSON object.

Solution

You need to escape special regular expression characters like / and ? before trying to use your pattern. For example, you could call Regexp#escape on the String like so:

Regexp.escape 'https://www.youtube.com/watch?v=hBIZF3sDFTI'
#=> "https://www\\.youtube\\.com/watch\\?v=hBIZF3sDFTI"

Then, assuming you have a valid JSON object, you could match the expression as follows:

require 'json'

str  = 'https://www.youtube.com/watch?v=hBIZF3sDFTI'
json = str.to_json
#=> "\"https://www.youtube.com/watch?v=hBIZF3sDFTI\""

pattern = Regexp.escape str
json.match pattern
#=> #<MatchData "https://www.youtube.com/watch?v=hBIZF3sDFTI">