正则表达式验证只有字符(非特殊字符)、空格和数字的字符串 [英] Regex to validate string having only characters (not special characters), blank spaces and numbers

查看:109
本文介绍了正则表达式验证只有字符(非特殊字符)、空格和数字的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby on Rails 3.0.9,我想验证一个只能包含字符(不是特殊字符 - 不区分大小写)、空格和数字的字符串.

I am using Ruby on Rails 3.0.9 and I would like to validate a string that can have only characters (not special characters - case insensitive), blank spaces and numbers.

在我的验证代码中:

validates :name,
  :presence   => true,
  :format     => { :with => regex } # Here I should set the 'regex'

我应该如何表述正则表达式?

How I should state the regex?

推荐答案

有几种方法可以做到这一点.如果您只想允许 ASCII 字字符(没有重音字符,如 Ê 或来自其他字母表的字母,如 Ӕ 或 ל),请使用:

There are a couple ways of doing this. If you only want to allow ASCII word characters (no accented characters like Ê or letters from other alphabets like Ӕ or ל), use this:

/^[a-zA-Z\d\s]*$/

如果您希望 Ruby 1.8.7 只允许来自其他语言的数字和字母,请使用:

If you want to allow only numbers and letters from other languages for Ruby 1.8.7, use this:

/^(?:[^\W_]|\s)*$/u

如果您希望 Ruby 1.9.x 只允许来自其他语言的数字和字母,请使用:

If you want to allow only numbers and letters from other languages for Ruby 1.9.x, use this:

^[\p{Word}\w\s-]*$

此外,如果您计划在 Ruby on Rails 中使用支持 unicode 的 1.9.x 正则表达式,请在 .rb 文件的开头添加以下行:

Also, if you are planning to use 1.9.x regex with unicode support in Ruby on Rails, add this line at the beginning of your .rb file:

# coding: utf-8

这篇关于正则表达式验证只有字符(非特殊字符)、空格和数字的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆