问题描述
我正在使用javascript验证器,它可以让我根据regexp构建自定义验证
I am using a javascript validator which will let me build custom validation based on regexp
从他们的网站: regexp = ^ [A- Za-z] {1,20} $
允许最多20个字母字符。
From their website: regexp=^[A-Za-z]{1,20}$
allow up to 20 alphabetic characters.
如果输入的数据在输入字段超出此范围。
This will return an error if the entered data in the input field is outside this scope.
如果值的第一个字符为asterix,则需要的是触发输入字段错误的字符串。
What I need is the string that will trigger an error for the inputfield if the value has an asterix as the first character.
我可以通过以下方式触发相反的操作(如果第一个字符不是星号则出错)
I can make it trigger the opposite (an error if the first character is NOT an asterix) with:
regexp=[\u002A]
Heeeeelp please :-D
Heeeeelp please :-D
推荐答案
怎么样:
^[^\*]
哪个匹配任何不的输入从星号开始;从示例正则表达式判断,任何与正则表达式不匹配的输入都将导致验证错误,因此使用双重否定您应该得到您想要的行为: - )
Which matches any input that does not start with an asterisk; judging from the example regex, any input which does not match the regex will be cause a validation error, so with the double negative you should get the behaviour you want :-)
我的正则表达式的解释:
Explanation of my regex:
- 第一个
^
表示在开始时字符串 -
[
...]
构造是一个字符class,括在括号中的单个字符 - 字符类开头的
^
表示否定字符类,即匹配不列出的字符之一 -
\ *
表示文字*
;*
在正则表达式中有特殊含义,所以我用反斜杠转义它。正如Rob在评论中指出的那样,在角色类中逃避(大多数)特殊字符并不是绝对必要的
- The first
^
means "at the start of the string" - The
[
...]
construct is a character class, which matches a single character among the ones enclosed within the brackets - The
^
in the beginning of the character class means "negate the character class", i.e. match any character that's not one of the ones listed - The
\*
means a literal*
;*
has a special meaning in regular expressions, so I've escaped it with a backslash. As Rob has pointed out in the comments, it's not strictly necessary to escape (most) special characters within a character class
这篇关于Javascript regexp - 仅当第一个字符不是星号时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!