【问题标题】:Use regex to allow for alphabetic characters, hypens, underscores, spaces, and numbers使用正则表达式允许字母字符、连字符、下划线、空格和数字
【发布时间】:2020-12-25 19:12:09
【问题描述】:

我想在一个独特的情况下验证使用 Laravel。我授权的字段是一本书的名称。所以它可以有字母字符、数字字符、空格和连字符/下划线/任何其他键。我唯一不希望它有空格,在你输入任何键之前。所以名字不能是“L”,注意空格,而“L L L”是完全可以接受的。在这种情况下有人可以帮助我吗?

到目前为止,我得到了一个正则表达式验证:

regex:[a-z{1}[A-Z]{1}[0-9]{1}]

我不确定如何包含其他限制。

【问题讨论】:

  • Laravel 5.4 为此添加了一个中间件 Trim Strings Middleware 这里是类 \Illuminate\Foundation\Http\Middleware\TrimStrings 所以不用担心额外的空格;)
  • 是的,我尝试使用 alpha_num 作为验证方法,但是当我使用诸如“L L L”之类的空格时,它说有错误。 ://
  • 尝试在您的验证规则中使用它'regex:/^[\w-]*$/'
  • @Maraboc 不走运:/ 它不允许我在两者之间添加空格。如果我写“L L L”,它会抛出一个错误。
  • 只需添加\s ==> 'regex:/^[\s\w-]*$/' :)

标签: laravel validation


【解决方案1】:
  • 简答:

对于带空格的 alpha_num,请使用此正则表达式:

'regex:/^[\s\w-]*$/'
  • 再长一点 :)

这里是一些已定义的正则表达式:

^           ==>  The circumflex symbol marks the beginning of a pattern, although in some cases it can be omitted
$           ==>  Same as with the circumflex symbol, the dollar sign marks the end of a search pattern
.           ==>  The period matches any single character
?           ==>  It will match the preceding pattern zero or one times
+           ==>  It will match the preceding pattern one or more times
*           ==>  It will match the preceding pattern zero or more times
|           ==>  Boolean OR
–           ==>  Matches a range of elements
()          ==>  Groups a different pattern elements together
[]          ==>  Matches any single character between the square brackets
{min, max}  ==>  It is used to match exact character counts
\d          ==>  Matches any single digit
\D          ==>  Matches any single non digit character
\w          ==>  Matches any alpha numeric character including underscore (_)
\W          ==>  Matches any non alpha numeric character excluding the underscore character
\s          ==>  Matches whitespace character

如果您想添加一些其他字符,您应该将其添加到 [] 块中。

例如,如果您想允许, ==> 'regex:/^[\s\w-,]*$/'

PS:如果你想要一个 setial char,比如我们 \ * 或 .你必须像这样 \ * 逃避它们。

对于* ==> 'regex:/^[\s\w-,\*]*$/'

【讨论】:

    【解决方案2】:

    检查这个模式:

    <?php
    
    $pattern = '/^(?=[^ ])[A-Za-z0-9-_ ]+$/';
    $test = ' L';
    
    if (preg_match($pattern, $test)) {
        echo 'matched';
    } else {
         echo 'does not match';   
    }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2012-12-12
      • 1970-01-01
      • 2020-07-07
      • 2022-01-14
      相关资源
      最近更新 更多