Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis Escape Special Character

Tags:

redis

How we can escape special characters in Redis search? I am sscan using to search for data from Redis using Match operation and my data having a special character in it like @#[]$& etc so How I can do it?

like image 424
Suraj Dalvi Avatar asked Nov 08 '25 10:11

Suraj Dalvi


1 Answers

Here's a function to escape characters on when inserting to redis. I believe all you need to do is add an extra slash to the replacement value when you're replacing a search value.

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

const newValue = value.replace(/,|\.|<|>|\{|\}|\[|\]|"|'|:|;|!|@|#|\$|%|\^|&|\*|\(|\)|-|\+|=|~/g, function(x) {
        return replacements[x]
})
return newValue
}
like image 83
Dane Stevens Avatar answered Nov 09 '25 23:11

Dane Stevens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!