2

Regex \w doesn't match utf-8 characters in Ruby 1.9.2. Anybody faced same problem?

Example:

/[\w\s]+/u

In my rails application.rb I've added config.encoding = "utf-8"

2 Answers 2

9

Define "doesn't match utf-8 characters"? If you expect \w to match anything other than exactly the uppercase and lowercase ASCII letters, the ASCII digits, and underscore, it won't -- Ruby has defined \w to be equivalent to [A-Za-z0-9_] regardless of Unicode. Maybe you want \p{Word} or something similar instead.

Ref: Ruby 1.9 Regexp documentation (see section "Character Classes").

7
  • That works in .NET. Looks like it is a bug of ruby regex implementation Oct 20, 2010 at 8:46
  • +1 Ruby has defined \w to be equivalent to [A-Za-z0-9_] regardless of Unicode. It's so obvious, so neither I don't noticed :)
    – kfl62
    Oct 20, 2010 at 8:56
  • 1
    As the answerer states, \p{Word} does the job - but it's Ruby 1.9 only. Could be worth checking whether Regexp.instance_methods.include?(:encoding) to figure out what pattern you want to use.
    – pat
    Jul 10, 2011 at 6:12
  • Could you please provide a reference for the postulate "Ruby has defined \w to be equivalent to [A-Za-z0-9_] regardless of Unicode."
    – Jarl
    Dec 7, 2011 at 13:51
  • @Jarl amended my answer. I can't find a definitive source for 1.8, but the meaning of \w in Ruby hasn't changed since... ever.
    – hobbs
    Dec 7, 2011 at 15:13
0

You could always use something like

[a-zA-Z0-9_ñáéíóú] 

instead of \w

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.