简体   繁体   English

RoR字符类正则表达式

[英]RoR character class regex

I have the following line of code in my Ruby on Rails app, which checks whether the given string contains Korean characters or not: 我在Ruby on Rails应用程序中有以下代码行,它检查给定字符串是否包含韩语字符:

isKorean = !/\p{Hangul}/.match(word).nil?

It works perfectly in the console, but raises a syntax error for the actual app: 它在控制台中运行良好,但会为实际应用程序引发语法错误:

invalid character property name {Hangul}: /\p{Hangul}/

What am I missing and how can I get it to work? 我错过了什么,我怎样才能让它发挥作用?

This is a character encoding issue, you need to add: 这是一个字符编码问题,您需要添加:

# encoding: utf-8

to the top of the Ruby file you're using that regex in. You can probably use any encoding that the character class you're using exists in instead of UTF-8 if you wish. 在你正在使用该正则表达式的Ruby文件的顶部。如果你愿意,你可以使用你正在使用的字符类而不是UTF-8的任何编码。 Note that in Ruby 2.0, UTF-8 is now the default, so this is not needed in Ruby 2.0+. 请注意,在Ruby 2.0中,UTF-8现在是默认值,因此Ruby 2.0+中不需要这样做。

This is known as a "magic comment". 这被称为“魔术评论”。 You can and should read more about encoding in Ruby 1.9 . 您可以而且应该在Ruby 1.9中阅读有关编码的更多信息。 Note that encoding in Rails views is handled automatically by config.encoding (set to UTF-8 by default in config/application.rb . 请注意,Rails视图中的编码由config.encoding自动处理(默认情况下在config/application.rb设置为UTF-8)。

It was likely working in the console because your terminal is set to use UTF-8 already. 它可能在控制台中工作,因为您的终端已设置为使用UTF-8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM