Javascript regexp - only if first character is not an asterisk

≯℡__Kan透↙ 提交于 2019-11-30 23:46:08

问题


I am using a javascript validator which will let me build custom validation based on regexp

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.

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


回答1:


How about:

^[^\*]

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:

  • 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



回答2:


How about ^[^\*].+.

Broken down:

  • ^ = start of string.
  • [^\*] = any one character not the '*'.
  • .+ = any other character at least once.



回答3:


You can invert character class by using ^ after [

regexp=[^\u002A]



来源:https://stackoverflow.com/questions/5293859/javascript-regexp-only-if-first-character-is-not-an-asterisk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!