Datasette 插件,添加自定义 SQL 函数,用于使用 Rust 正则表达式引擎执行匹配
在与 Datasette 相同的环境中安装此插件以启用 regexp()
SQL 函数。
$ pip install datasette-rure
该插件基于 David Blewett 的 rure-python 库构建。
您可以像这样测试一个值是否匹配正则表达式
select regexp('hi.*there', 'hi there')
-- returns 1
select regexp('not.*there', 'hi there')
-- returns 0
您也可以使用 SQLite 的自定义语法运行匹配
select 'hi there' REGEXP 'hi.*there'
-- returns 1
这意味着您可以根据正则表达式匹配来选择行 - 例如,选择所有标题以 E 或 F 开头的文章
select * from articles where title REGEXP '^[EF]'
试一试:REGEXP 互动演示
您可以使用 regexp_match()
提取模式中捕获的子集。
select regexp_match('.*( and .*)', title) as n from articles where n is not null
-- Returns the ' and X' component of any matching titles, e.g.
-- and Recognition
-- and Transitions Their Place
-- etc
当有两个参数时,这将返回第一个括号匹配项。您可以使用三个参数来指示您希望提取哪个匹配项
select regexp_match('.*(and)(.*)', title, 2) as n from articles where n is not null
对于无效输入(例如没有捕获组的模式),函数将返回 null
。
regexp_matches()
函数可用于从单个字符串中提取多个模式。结果以 JSON 数组的形式返回,然后可以使用 SQLite 的 JSON 函数进一步处理。
第一个参数是带有命名捕获组的正则表达式。第二个参数是要匹配的字符串。
select regexp_matches(
'hello (?P\w+) the (?P\w+)',
'hello bob the dog, hello maggie the cat, hello tarquin the otter'
)
这将返回一个 JSON 对象列表,每个对象代表原始正则表达式中的命名捕获项
[
{"name": "bob", "species": "dog"},
{"name": "maggie", "species": "cat"},
{"name": "tarquin", "species": "otter"}
]