在mongoose中使用正则表达式过滤部分单词?

huangapple go评论51阅读模式
英文:

Regex filtering in mongoose with partial words?

问题

我正在尝试根据一个字符串进行过滤结果。
例如- 我要找到 'Sanam Suhag'。

当我键入 's su' 时,这将找到正确的结果。

但如果第一个单词包含超过1个字母,那么我必须使用完整的第一个单词,否则它将返回空数组。

router.get('/filter/:keywords', (req, res) => {
    console.log('后端接收到的关键字...', req.params.keywords);
    var regex = new RegExp(req.params.keywords, "i");
    var itemFound = Item.find({ name: regex, "status.active": true }, { 'name': 1 }).sort({ "updated_at": -1 }).sort({ "created_at": -1 }).limit(20);
    itemFound.exec((err, data) => {
        console.log(data);
        var result = [];
        if (!err) {
            if (data && data.length && data.length > 0) {
                data.forEach(item => {
                    let itemObj = item;
                    result.push(itemObj);
                });
            }
            res.send(result);
        }
        if (err) {
            console.log(err);
        }
    });
});

需要查找 - Sanam Suhag

对于 's su' 查询结果 - [{name - Sanam Suhag}]

对于 'san suhag' 查询结果 - []

英文:

I am trying to filter result based on a string.
For example- i have to find 'Sanam Suhag'.

When i type 's su' <= this will find the proper result.

But if first word have more then 1 alphabet then i will have to use full first word otherwise it will return empty array.

    router.get(&#39;/filter/:keywords&#39;, (req, res) =&gt; {

    console.log(&#39;Keyword recieved in backend ...&#39;, req.params.keywords);

    var regex = new RegExp(req.params.keywords, &quot;i&quot;)
    var itemFound = Item.find({ name: regex, &quot;status.active&quot;: true }, { &#39;name&#39;: 1 }).sort({ &quot;updated_at&quot;: -1 }).sort({ &quot;created_at&quot;: -1 }).limit(20);
    itemFound.exec((err, data) =&gt; {
        console.log(data);
        var result = [];
        if (!err) {
            if (data &amp;&amp; data.length &amp;&amp; data.length &gt; 0) {
                data.forEach(item =&gt; {
                    let itemObj = item
                    result.push(itemObj)
                });
            }
            res.send(result)
        }
        if (err) {
         console.log(err);  
        }
    })
});

Need to find - Sanam Suhag

for 's su' query result - [{name - Sanam Suhag}]

For 'san suhag' query result - []

答案1

得分: 1

请提供正则表达式模式,根据搜索输入来实现逻辑。

总结实现步骤:

  1. 按空格拆分搜索输入 (req.params.keywords)。

  2. 如果第一个词 (firstWord) 多于1个字符,则应使用以下模式:

^(?:${firstWord})\s(?:${wordsAfterFirstWord})

演示正则表达式模式1 @ Regex 101

  1. 否则,应使用以下模式:
^(?:${firstWord}[\w]+)\s(?:${wordsAfterFirstWord})

演示正则表达式模式2 @ Regex 101

对于调用者:

var regex = getRegexForName(req.params.keywords);
英文:

You should implement the logic to provide the Regex pattern according to the search input.

To summarize the implementation:

  1. Split the search input (req.params.keywords) by space.

  2. If the first word (firstWord) has more than 1 character, you should use this pattern:

^(?:${firstWord})\s(?:${wordsAfterFirstWord})

Demo Regex pattern 1 @ Regex 101

  1. Otherwise, you should use this pattern:
^(?:${firstWord}[\w]+)\s(?:${wordsAfterFirstWord})

Demo Regex pattern 2 @ Regex 101

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let value = &quot;Sanam Sunag&quot;;

// Text search input: &quot;s su&quot;
console.log(&quot;Search pattern: &#39;s su&#39;, Result: &quot;, getRegexForName(&quot;s su&quot;).exec(value));


// Text search input: &quot;sam su&quot;
console.log(&quot;Search pattern: &#39;sam su&#39;, Result: &quot;, getRegexForName(&quot;sam su&quot;).exec(value));

function getRegexForName(textSearch) {
    let regexPattern = null;
    
    if (!textSearch)
        return new RegExp(&quot;&quot;, &quot;i&quot;);

    let words = textSearch.split(&quot; &quot;);
    let firstWord = words[0];
    let wordsAfterFirstWord = words.slice(1).join(&#39; &#39;);
    if (words.length == 1)
        return new RegExp(firstWord, &quot;i&quot;); // Or your desired regex pattern that match if the textSearch has single word only

    if (firstWord.length &gt; 1)
        regexPattern = `^(?:${firstWord})\\s(?:${wordsAfterFirstWord})`;
    else
        regexPattern = `^(?:${firstWord}[\\w]+)\\s(?:${wordsAfterFirstWord})`;

    return new RegExp(regexPattern, &quot;i&quot;);
}

<!-- end snippet -->

For the caller:

var regex = getRegexForName(req.params.keywords);

huangapple
  • 本文由 发表于 2023年6月29日 13:00:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定