如何使用matches(regex)验证用户名? [英] How to validate usernames using matches(regex)?

查看:62
本文介绍了如何使用matches(regex)验证用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下表达式放入matchs函数中,但是在尝试编译规则时我猜错了.

I'm trying to put the following expression into the matches function but I guess errors when trying to compile the rules.

 ^[a-zA-Z](([\._\-][a-zA-Z0-9])|[a-zA-Z0-9])*[a-z0-9]$

.validate规则如下:

".validate": "newData.val() === auth.uid         
&& newData.val().matches(^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$)" 

我得到:

" Invalid escape: '\.'"

推荐答案

看来您无法在Firebase中使用环顾四周,因此应调整您的模式和整个方法以解决此问题.

It appears you cannot use lookarounds in Firebase, so your pattern and the whole approach should be adjusted to account for that.

您当前的正则表达式需要5到10个符号的字符串长度,并且不允许使用两个连续的符号._-.第一个条件应使用诸如newData.val().length >= 5 && newData.val().length <= 10之类的代码在正则表达式之外进行检查,第二个条件仅需要重新分组和重新量化:

Your current regex requires a string length from 5 to 10 symbols, and disallows 2 consecutive symbols ., _ and -. The first condition should be checked outside the regex with some code like newData.val().length >= 5 && newData.val().length <= 10 and the second one just requires re-grouping and re-quantifying:

.matches(/^[a-z][a-z0-9]*([._-][a-z0-9]+)*$/)

请参见正则表达式演示.

详细信息:

  • ^-字符串开头
  • [a-z]-小写字母(如果在末尾添加/i,将区分大小写)
  • [a-z0-9]*-零个或多个a-z0-9符号
  • ([._-][a-z0-9]+)*-一个._-,后跟一个或多个(如果存在.,<字符串中的c2>或-)来自0-9a-z范围的字符
  • $-字符串锚点的结尾.
  • ^ - start of string
  • [a-z] - a lowercase letter (if you add /i at the end, it will be case sensitive)
  • [a-z0-9]* - zero or more a-z and 0-9 symbols
  • ([._-][a-z0-9]+)* - a ., _ or - followed with one or more (this requires [a-z0-9] to be at the end if there is ., _ or - in the string) characters from 0-9 and a-z ranges
  • $ - the end of string anchor.

请注意,您不必转义字符类中的字符,因为其中的._不是特殊字符,并且-在方括号表达式(字符类)的末尾或开头是文字连字符.

Note you do not need to escape the characters inside the character class as the . and _ are not special chars inside it, and the - at the end or start of the bracket expression (character class) is a literal hyphen.

这篇关于如何使用matches(regex)验证用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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