为什么我写的正则表达式不能正常工作?

2024-09-28 18:54:55 发布

您现在位置:Python中文网/ 问答频道 /正文

pattern = '(ns:m\.[^ ]+ )|(ns:g\.[^ ]+ )'
query = "PREFIX ns: <http://rdf.freebase.com/ns/>\nSELECT DISTINCT ?x\nWHERE {\nFILTER (?x != ns:m.0pz91)\nFILTER (!isLiteral(?x) OR lang(?x) = '' OR langMatches(lang(?x), 'en'))\nns:m.0pz91 ns:film.producer.film ?x .\n?x ns:film.film.genre ?c .\n?c ns:film.film_genre.films_in_this_genre ns:g.11b5lzm6b0 . \n}"
entities = re.findall(pattern, query)

我要做的是在我的查询中查找所有freebase实体,即在我的示例中的'ns:g.11b5lzm6b0''ns:m.0pz91'。但是,我编写的代码返回[('ns:m.0pz91)\nFILTER ', ''), ('ns:m.0pz91 ', ''), ('', 'ns:g.11b5lzm6b0 ')],而不是['ns:m.0pz91 ', 'ns:g.11b5lzm6b0 ']
我通过使用两个独立的正则表达式解决了这个问题,即ns:m\.[^ ]+ns:g\.[^ ]+,但是,我仍然不明白为什么不能直接使用(ns:m\.[^ ]+ )|(ns:g\.[^ ]+ )来匹配ns:m\.[^ ]+ns:g\.[^ ]+。你知道吗


Tags: orcomhttplangprefixrdfquerypattern
2条回答

试试这个:

\sns:m\.\w*|\sns:g\.\w*

你的正则表达式不能工作是因为\n和你匹配的不是spacedemo

您可以参考演示url右侧的说明。你知道吗

你可以试试

(ns:[mg]\.\w+)

demo

更新

在原始正则表达式的输出中存在元组的原因是什么?你知道吗

文件上说:

this will be a list of tuples if the pattern has more than one group

你的正则表达式有两个捕获组。你知道吗

相关问题 更多 >