【问题标题】:MongoDB RegEx not finding any results when string contains parenthesis当字符串包含括号时,MongoDB RegEx 找不到任何结果
【发布时间】:2022-01-27 08:50:20
【问题描述】:

当使用正则表达式允许不区分大小写时,它仅适用于纯字符串。当 name 使用括号或其他特殊字符时,db 查询不返回任何结果。

示例:“Push It”可以正常工作并返回歌曲。然而,当搜索“Escape (The Pina Colada Song)”时,它没有返回任何歌曲。如何使正则表达式允许这些特殊字符?

任何建议都会很棒。

const lowercaseName = new RegExp(`^${name}`, 'i')
const songs: any = await Song.find({ name: lowercaseName, artist_id })

【问题讨论】:

标签: javascript typescript mongodb mongoose


【解决方案1】:

您应该转义您发送的字符串中的所有特殊字符。试试这个:

const lowercaseName = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, 'i')
const songs: any = await Song.find({ name: lowercaseName, artist_id })

【讨论】:

    猜你喜欢
    • 2019-11-25
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多