It if is a hex string, then it is not a string, you are just looking at
it as a string You ‘might’ handle it as a string, but in this case
you mix Unicode and non-Unicode characters in it (if we try to treat
each byte or multi-byte as a character).
So even if I force the encoding of UTF-8, it will fail (\xaa is not a
valid Unicode character)
" sss\1\2abc\xAA sss ".force_encoding(Encoding::UTF_8).valid_encoding?
If you don’t need to recognize multi-byte characters then deep dive into
the byte representation and search there:
" sss\1\2abc\xAA sss ".unpack(“H*”)
" sss\1\2abc\xAA sss ".unpack(“H*”).scan(/0102(.*)aa/)
You can turn the result easily to character string: