问题
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
rule looks as follows:
".validate": "newData.val() === auth.uid
&& newData.val().matches(^(?=.{5,10}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$)"
I get:
" Invalid escape: '\.'"
回答1:
It appears you cannot use lookarounds in Firebase, so your pattern and the whole approach should be adjusted to account for that.
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]+)*$/)
See the regex demo.
Details:
^
- 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 morea-z
and0-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 from0-9
anda-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.
来源:https://stackoverflow.com/questions/39503825/how-to-validate-usernames-using-matchesregex