I have a problem with replacing (gsub) a specific character in a string. This is the string I have:

string = "\n\t Tel.:\xA007031 / 11 11 11"

The \xA0 is not a character I want, so I try to replace it with \x20 (both are whitespace characters). To do so I call gsub on it:

string.gsub(' ', ' ')

When trying to do that it returns an "incompatible encoding regexp match (UTF-8 regexp with ISO-8859-1 string)" error.

Any thoughts on how to fix that will be much appreciated!

有帮助吗?

解决方案

You can do this -

string.force_encoding("ISO-8859-1").gsub(/:./,":") 
#=> "\n\t Tel.:07031 / 11 11 11"

And if you want to encode it in UTF-8 then do this -

string.force_encoding("ISO-8859-1").encode!("UTF-8")
#=> "\n\t Tel.: 07031 / 11 11 11"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top