我们一般使用正则来匹配字符串。我想反过来做。我有大量的正则表达式。现在,给定一个字符串,我应该确定哪个正则表达式与该字符串匹配。我该怎么做?
我正在考虑将所有正则表达式存储在 Elasticsearch 中,然后使用字符串查询它,但我找不到任何文档来查看是否可行。
我可以将所有正则表达式存储在一个数据库中,获取我想要检查匹配项然后找到匹配项的正则表达式,但是有没有更好的方法来做到这一点?
percolator
字段类型来做到这一点。
regexp
查询,然后测试哪些查询会匹配你的文档。
使用过滤器字段类型创建索引:
PUT regex
{
"mappings": {
"properties": {
"message": {
"type": "keyword"
},
"query": {
"type": "percolator"
}
}
}
}
索引两个正则表达式,例如:
PUT /regex/_doc/1
{
"query": {
"regexp": {
"message": {
"value": "big.*fox",
"flags": "ALL",
"case_insensitive": true
}
}
}
}
PUT /regex/_doc/2
{
"query": {
"regexp": {
"message": {
"value": ".*fox",
"flags": "ALL",
"case_insensitive": true
}
}
}
}
然后测试哪个正则表达式与您的输入匹配。
渗透
big brown fox
将匹配上面的两个正则表达式:
POST regex/_search
{
"query": {
"percolate": {
"field": "query",
"document": {
"message": "big brown fox"
}
}
}
}
渗滤
big brown bear
将不符合以上任何一项:
POST regex/_search
{
"query": {
"percolate": {
"field": "query",
"document": {
"message": "big brown bear"
}
}
}
}