简体   繁体   English

Rails正则表达式验证字符串转义

[英]rails regular expression validation string escape

I have a name attribute in my model which is validated by 我的模型中有一个名称属性,该属性已通过验证

validates :name ,format:{with: /^[\p{L} \.'\-]+$/ , message: "invalid name" }

The following syntax error was found while creating an object of the model 创建模型对象时发现以下语法错误

SyntaxError (basic_info.rb:8: invalid  property name {L}: /^[\p{L} \.'\-]+$/

Apparently Ruby is trying to evaluate {L} inside the regex which is undefined. 显然,Ruby试图在未定义的正则表达式中评估{L} Also inserting escape characters inside the regex would make it invalid. 另外在正则表达式中插入转义字符会使它无效。

Edit: According to this post it's to do with encoding. 编辑:根据这篇文章,它与编码有关。 Pre-Ruby 2.0.0, the default encoding for ruby scripts is not Unicode, so this'll be causing you issues when using a unicode character property regexp pattern ( \\p{L} for example!). 在Ruby 2.0.0之前的版本中,ruby脚本的默认编码不是Unicode,因此在使用unicode字符属性regexp模式(例如\\p{L} !)时,这将导致您出现问题。

You need to put the magic # encoding: utf-8 comment at the top of your file. 您需要在文件顶部添加神奇的# encoding: utf-8注释。


I just did a quick IRB test, but are you using Ruby 1.8.7 by any chance? 我刚刚进行了快速的IRB测试,但是您是否正在使用Ruby 1.8.7?

In 1.8.7: 在1.8.7中:

>> "blah".match(/^[\p{L} \.'\-]+$/)
=> nil

in 2.0.0: 在2.0.0中:

>> "blah".match(/^[\p{L} \.\-']+$/)
=> #<MatchData "blah">

Seems 1.8.7 Regexp doesn't support unicode character properties? 似乎1.8.7 Regexp不支持Unicode字符属性? Consider using /^[a-zA-Z \\.'\\-]+$/ instead. 考虑改用/^[a-zA-Z \\.'\\-]+$/

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

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