我会使用这样的正则表达式:
/link\s*\(([^\)\s]+)\s*([^\)]+)?\)/i
这将找到以单词 link 开头的任何匹配项,后跟任意数量的空格,然后是 url,后跟链接名称,都在括号中。在这个正则表达式中,链接名称是可选的,但 url 不是。匹配不区分大小写,所以会匹配link 和LINK 完全相同。
您可以使用Regexp#match 方法将正则表达式与字符串进行比较,并检查匹配和捕获的结果,如下所示:
m = /link\s*\(([^\)\s]+)\s*([^\)]+)?\)/i.match("link (stackoverflow.com StackOverflow)")
if m # the match array is not nil
puts "Matched: #{m[0]}"
puts " -- url: {m[1]}"
puts " -- link-name: #{m[2] || 'none'}"
else # the match array is nil, so no match was found
puts "No match found"
end
如果您想使用不同的字符串来识别匹配项,您可以使用 non-capturing 组,将link 更改为:
(?:link|site|website|url)
在这种情况下,(?: 语法表示不捕获这部分匹配。如果要捕获匹配的术语,只需将其从 (?: 更改为 (,并将捕获索引调整 1 以考虑新的捕获值。
这是一个简短的 Ruby 测试程序:
data = [
[ true, "link (http://google.com Google)", "http://google.com", "Google" ],
[ true, "LiNk(ftp://website.org)", "ftp://website.org", nil ],
[ true, "link (https://facebook.com/realstanlee/ Stan Lee) linkety link", "https://facebook.com/realstanlee/", "Stan Lee" ],
[ true, "x link (https://mail.yahoo.com Yahoo! Mail)", "https://mail.yahoo.com", "Yahoo! Mail" ],
[ false, "link lunk (http://www.com)", nil, nil ]
]
data.each do |test_case|
link = /link\s*\(([^\)\s]+)\s*([^\)]+)?\)/i.match(test_case[1])
url = link ? link[1] : nil
link_name = link ? link[2] : nil
success = test_case[0] == !link.nil? && test_case[2] == url && test_case[3] == link_name
puts "#{success ? 'Pass' : 'Fail'}: '#{test_case[1]}' #{link ? 'found' : 'not found'}"
if success && link
puts " -- url: '#{url}' link_name: '#{link_name || '(no link name)'}'"
end
end
这会产生以下输出:
Pass: 'link (http://google.com Google)' found
-- url: 'http://google.com' link_name: 'Google'
Pass: 'LiNk(ftp://website.org)' found
-- url: 'ftp://website.org' link_name: '(no link name)'
Pass: 'link (https://facebook.com/realstanlee/ Stan Lee) linkety link' found
-- url: 'https://facebook.com/realstanlee/' link_name: 'Stan Lee'
Pass: 'x link (https://mail.yahoo.com Yahoo! Mail)' found
-- url: 'https://mail.yahoo.com' link_name: 'Yahoo! Mail'
Pass: 'link lunk (http://www.com)' not found
如果您想在单词“链接”和第一个括号之间允许除空格以外的任何内容,只需将 \s* 更改为 [^\(]* 即可。