1

When running a ruby script with regex,

s = object.value.gsub(/(\A[\s\xA0]*|[\s\xA0]*\Z)/n, '')

Got error

invalid multibyte escape: /(\A[\s\xA0]*|[\s\xA0]*\Z)/ (SyntaxError)

Any idea why? Ruby version 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

1 Answer 1

5

\xHH syntax is only valid for UTF-8 characters \x00 to \x7F. \x80 to \xFF are valid in US-ASCII encoding, but not UTF-8; to use higher characters in UTF-8, use \uHHHH. Thus, these all work:

/\u00A0/

/#{"\\xA0".encode('US-ASCII')}/

Regexp.new("\\xA0".encode('US-ASCII'))

# encoding: US-ASCII
/\xA0/

although they do different things, depending on what encoding you are matching. For example:

# encoding: UTF-8
Regexp.new("\\xA0".encode('US-ASCII')) =~ "\u00A0"
# => Encoding::CompatibilityError: incompatible encoding regexp match (ASCII-8BIT regexp with UTF-8 string)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.