我正在为我从头开始编码的博客开发自定义搜索功能。该博客面向技术型读者,我希望读者可以通过在搜索字段中定义一些高级搜索条件来搜索文章(而不是使用多个搜索输入,一个用于标题,一个用于标签,一个用于类别..等等)。有点类似于 Jiras advanced search或谷歌search operators .
我将用 Javascript 进行编码,但我将使用 xRegExp 库,它支持 native RegExp 不支持的所有很酷的功能(命名组匹配、向前查找、向后查找等)
可搜索的“字段”是:
- 标题
- 摘要
- 作者
- 类别
- 标签
- 创建(日期)
- 更新(日期)
- (未指定字段)一般搜索短语
要将搜索“字段”添加到搜索条件,您只需键入上面的字段名称之一,然后输入冒号 (:
),然后输入搜索与该字段相关的短语。
除此之外,我还希望允许查看者在搜索条件中添加一些“OR”和“AND”逻辑,例如搜索文章作者为 john.doe OR mike.smith,或带有标签 bash AND 脚本。 OR 运算符可以是 ||
,AND 运算符可以是 &&
。
一些示例搜索字符串:
author:linus tag:linux How Linux got started
- 作者:Linus
- 标签:Linux
- 一般搜索短语:Linux 的入门方式
author:john.doe||jane.smith categories:infosec||linux tags:linux&&security Securing your first Linux server
- 作者:john.doe 或 jane.smith
- 类别:信息安全 或 Linux
- 标签:Linux 或 安全性
- 一般搜索短语:保护您的第一个 Linux 服务器
问题
我希望通过正则表达式尽可能多地完成字符串解析。我发生了一些事情 regex101 ,但我在多次匹配模式时遇到问题,并用空格分隔。因此,任何帮助将不胜感激。谢谢!
最佳答案
ps。抱歉我没有使用你的lib。我通常只会在确实需要时才使用库。没有仔细阅读您的消息。除此之外,我认为代码是可读/易于编辑的(与大多数正则表达式不同)。
我也看到了nodejs标签,如果您使用它来“发送”,您可以轻松地将这些对转换为键/值,如下所示:
const pairSeperator = ':';
const valueSeperators = [
{ splitter: '||', replacingValue: 'OR' },
{ splitter: '&&', replacingValue: 'AND' },
];
const validKeyNames = [
'title',
'summary',
'author',
'category',
'tag',
'created',
'updated',
];
function isValidKeyValuePair(input) {
const possiblePair = input.split(pairSeperator);
if (possiblePair.length == 2) {
return validKeyNames.indexOf(possiblePair[0]) > -1;
}
return false;
}
function parseValue(value) {
const valueSeperator = valueSeperators.find((s) => value.indexOf(s.splitter) > -1);
if (valueSeperator) {
return value
.split(valueSeperator.splitter)
.join(` ${valueSeperator.replacingValue} `);
}
return value;
}
function pairReduce(memo, strPair) {
const [key, value] = strPair.split(pairSeperator);
obj[key] = parseValue(value);
return obj;
}
// this is function which handles your searchTerm
function parseSearch(searchTerm) {
const splittedSearchTerm = searchTerm.split(' ');
const filters = splittedSearchTerm
.filter(isValidKeyValuePair)
.reduce(pairReduce, {});
const searchTerm = splittedSearchTerm
.filter(input => !isKeyValuePair(input))
.join(' ');
return Object.assign(filters, { searchTerm });
// input: parseSearch("tag:linux why Linux rocks?");
// output: { "tag": "linux", "searchTerm": "why Linux rocks?" }
}
关于javascript - 解析单个用户输入字符串以获取高级搜索条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691386/