If we have a key that holds a string value, we can use the GETRANGE
command to get a substring from that value.
Redis also has a SUBSTR
command that does the same thing, but that was deprecated in Redis 2.0.0, in favour of the GETRANGE
command.
Example
Suppose we get the full value from the following key:
GET fruit
Result:
"Mangosteen"
We can use GETRANGE
to get a substring from that string:
GETRANGE fruit 1 4
Result:
"ango"
The count starts at 0
and so 1
returns the second character. We specified 4
for the end of the substring.
Here’s another example using the same key:
GETRANGE fruit 3 6
Result:
"gost"
Negative Offsets
We can use negative offsets if required.
The negative offset works backwards from the end of the string:
GETRANGE fruit -3 -1
Result:
"een"