Redis 转义特殊字符

Sur*_*lvi 3 redis

我们如何在Redis搜索中转义特殊字符?我使用 sscan 使用 Match 操作从 Redis 中搜索数据,并且我的数据中有特殊字符,如 @#[]$& 等,那么我该怎么做呢?

小智 5

这是一个在插入到 redis 时转义字符的函数。我相信您需要做的就是在替换搜索值时向替换值添加一个额外的斜杠。

function redisReplace(value) {
const replacements = {
    ',': '\\,', 
    '.': '\\.',
    '<': '\\<',
    '>': '\\>',
    '{': '\\{',
    '}': '\\}',
    '[': '\\[',
    ']': '\\]',
    '"': '\\"',
    "'": "\\'",
    ':': '\\:',
    ';': '\\;',
    '!': '\\!',
    '@': '\\@',
    '#': '\\#',
    '$': '\\$',
    '%': '\\%',
    '^': '\\^',
    '&': '\\&',
    '*': '\\*',
    '(': '\\(',
    ')': '\\)',
    '-': '\\-',
    '+': '\\+',
    '=': '\\=',
    '~': '\\~',
}

const newValue = value.replace(/,|\.|<|>|\{|\}|\[|\]|"|'|:|;|!|@|#|\$|%|\^|&|\*|\(|\)|-|\+|=|~/g, function(x) {
        return replacements[x]
})
return newValue
}
Run Code Online (Sandbox Code Playgroud)