Ruby 1.9 unicode comes in regexp

I just upgraded an old project to Ruby 1.9.3. I'm having problems with unicode strings. It comes down to:

p = "\\username"; "Any String".match(/#{p}/) 

This works in 1.8 and returns zero as expected. However, in 1.9 he throws:

 ArgumentError: invalid Unicode escape 

I am trying to match '\u' in a string. I thought that two backslashes could not register it as Unicode.

What am I missing here?

Edit: single quotes don't work either:

 1.9.3p429 :002 > p = '\\username'; "Any String".match(/#{p}/) ArgumentError: invalid Unicode escape from (irb):2 
+4
source share
1 answer

When you execute /#{p}/ , this means that p will be interpreted as a regular expression. Since your p now \username , this compilation of Regexp will fail (since this is an invalid Unicode escape sequence):

 >> Regexp.new "\\username" RegexpError: invalid Unicode escape: /\username/ 

those. execution /#{p}/ is equal to the entry /\username/ .

Therefore, you need to avoid p from any regular expressions so that it is correctly interpreted:

 "Any String".match(/#{Regexp.escape(p)}/) 

Or simply:

 "Any String".match(Regexp.escape(p)) 
+3
source

Source: https://habr.com/ru/post/1484349/


All Articles