使用SPARQL提取包含特定子字符串的三元组

use*_*580 13 regex sparql

我想在其主题中提取一个包含单词"alice"的三元组.我使用的查询是:

SELECT ?s ?p ?o  WHERE { ?s ?p ?o .FILTER regex(?s, \"alice\") .}
Run Code Online (Sandbox Code Playgroud)

尽管有三重满足这个约束,但这并没有给我任何结果.

另一方面,当我使用相同的查询来提取在其对象中包含单词brillant的三元组时.它仅返回2个可能匹配中的一个.

使用的查询是:

SELECT ?s ?p ?o  WHERE { ?s ?p ?o .FILTER regex(?o, \"brillant\") .}
Run Code Online (Sandbox Code Playgroud)

请让我知道我哪里出错了,这种行为的原因是什么.

Jos*_*lor 18

我会假设引号周围的转义只是复制和粘贴的残余.正则表达式的第一个参数必须是文字,但文字不能成为RDF中三元组的主题,因此您拥有的数据不应该与此模式匹配.但是,您可能拥有的主题是URI,其URI包含字符串"alice",您可以使用str函数获取URI的字符串表示形式.例如,

SELECT ?s ?p ?o  WHERE { ?s ?p ?o .FILTER regex(str(?s), "alice") .}
Run Code Online (Sandbox Code Playgroud)

为了说明,让我们使用这两个值<http://example.org>"string containing example"像在原始查询中那样进行过滤:

select ?x where {
  values ?x { <http://example.org> "string containing example" }
  filter( regex(?x, "exam" ))
}
Run Code Online (Sandbox Code Playgroud)
-------------------------------
| x                           |
===============================
| "string containing example" |
-------------------------------
Run Code Online (Sandbox Code Playgroud)

我们只得到"string containing example"因为另一个值不是字符串,因此不适合regex.但是,如果我们将调用添加到str,那么它是regex将考虑的URI的字符串表示:

select ?x where {
  values ?x { <http://example.org> "string containing example" }
  filter( regex(str(?x), "exam" ))
}
Run Code Online (Sandbox Code Playgroud)
-------------------------------
| x                           |
===============================
| <http://example.org>        |
| "string containing example" |
-------------------------------
Run Code Online (Sandbox Code Playgroud)

  • @DieterDP DBpedia使用Virtuoso作为其端点.它的实现"有帮助"扩展**正则表达式**接受非字符串,即使标准说[**regex**](http://www.w3.org/TR/sparql11-query/#func- regex)以文字为参数.我说"有帮助",因为虽然它可能使Virtuoso的查询更简单,但最终会导致非便携式查询在您将其带到其他环境时失败.如果您关注可移植性并遵守标准,则可以在[sparql.org的通用查询引擎](http://sparql.org/sparql.html)上测试查询. (3认同)
  • 只是想提一下,对于有问题的精确查询,“contains()”的工作方式与“regex()”相同或更正确(因为它需要文字字符串) (2认同)