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

string-使用ruby在json文件中查找youtube url

(string - Find youtube url in json file with ruby)

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

出于测试目的,我的json文件(test.json)仅包含我要查找的字符串:

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

不知何故,我无法使用以下Ruby代码在文件中找到字符串:

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

  puts("string not in file")
end

输出:“字符串不在文件中”

但是字符串在文件中。

搜索其他字符串可以正常工作,因此此特定字符串一定是有问题的。

任何帮助深表感谢!

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

问题

你的正则表达式模式无效,因为其中包含太多的正斜杠。具体来说:

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

不是一个有效的正则表达式。你的String也不是有效的JSON对象。

解决方案

在尝试使用模式之前,你需要转义特殊的正则表达式字符(例如/和)?例如,你可以像这样在String上调用Regexp#escape

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

然后,假设你具有有效的JSON对象,则可以按以下方式匹配表达式:

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