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!
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.
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">
"isn't valid, because it's got too many forward slashes" – how many slashes are okay? ;-)
@Stefan I know you're being humorous, but for the benefit of future visitors, the standard regex literals (e.g. not useing
%r
) can have zero unescaped forward slashes within the expression. I suppose the OP could have solved part of the problem with%r{https://www.youtube.com/watch?v=hBIZF3sDFTI}
, but that just kicks the can down the road since any literal constructor might need to be escaped in some future string.And even in
%r
you have to escape.
and?
, soRegexp.escape
is the way to go. However, note that it returns a string. You probably wantpattern
to be a regexp. (your example works nonetheless becausematch
converts it, but that might not be obvious)great, thanks for the help!