Ruby中的全名正则表达式

时间:2014-04-18 16:22:31

标签: ruby-on-rails regex validation whitespace

我知道有很多类似的问题,但我无法在任何地方找到我的案例。

我正在尝试在Ruby on Rails用户模型中编写全名RegEx 。 它应验证名字和姓氏是否填充了一个空格。两个名称都应包含至少2个字符(例如:Li Ma)。

作为奖励,但我没有必要将空白修剪为一个字符,以防用户输入错误并输入多个空格(例如:李马将被修剪为李马) 目前我正在验证它(警告:可能不正确):

validates :name,
        presence: true,
        length: {
            maximum: 64,
            minimum: 5,
            message: 'must be a minimum: 5 letters and a maximum: 64 letters'},
        format: {
            # Full Name RegEx
            with: /[\w\-\']+([\s]+[\w\-\']){1}/
        }

这适用于我,但不检查每个名称的最少2个字符(例如:Peter P现在是正确的)。这也接受了多个不太好的空格(例如:Peter P)

我知道识别名称的这个问题非常以文化为中心,可能不是验证全名的正确方法(也许有人有一个字符名称),但这是当前的要求。

我不想将此字段拆分为2个不同的字段名字和姓氏,因为它会使用户界面复杂化。

2 个答案:

答案 0 :(得分:1)

您可以匹配以下regex

/([\w\-\']{2,})([\s]+)([\w\-\']{2,})/

并替换为:(假设它支持捕获组)

'\1 \3'$1 $3无论语法是什么:

它消除了额外的空白,只保留一个,如你所愿。

演示:http://regex101.com/r/oQ6aO7

答案 1 :(得分:0)

result = subject.gsub(/\A(?=[\w' -]{5,64})([\w'-]{2,})([\s]{1})\s*?([\w'-]{2,})\Z/, '\1\2\3')

http://regex101.com/r/dT1fJ4

Assert position at the beginning of the string «^»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=[\w' -]{5,64})»
   Match a single character present in the list below «[\w' -]{5,64}»
      Between 5 and 64 times, as many times as possible, giving back as needed (greedy) «{5,64}»
      A word character (letters, digits, and underscores) «\w»
      The character “'” «'»
      The character “ ” « »
      The character “-” «-»
Match the regular expression below and capture its match into backreference number 1 «([\w'-]{2,})»
   Match a single character present in the list below «[\w'-]{2,}»
      Between 2 and unlimited times, as many times as possible, giving back as needed (greedy) «{2,}»
      A word character (letters, digits, and underscores) «\w»
      The character “'” «'»
      The character “-” «-»
Match the regular expression below and capture its match into backreference number 2 «([\s]{1})»
   Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «[\s]{1}»
      Exactly 1 times «{1}»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regular expression below and capture its match into backreference number 3 «([\w'-]{2,})»
   Match a single character present in the list below «[\w'-]{2,}»
      Between 2 and unlimited times, as many times as possible, giving back as needed (greedy) «{2,}»
      A word character (letters, digits, and underscores) «\w»
      The character “'” «'»
      The character “-” «-»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»