Javascript regexp - 仅当第一个字符不是星号时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5293859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:31:38  来源:igfitidea点击:

Javascript regexp - only if first character is not an asterisk

javascriptregexnegate

提问by Splynx

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

我正在使用一个 javascript 验证器,它可以让我基于正则表达式构建自定义验证

From their website: regexp=^[A-Za-z]{1,20}$allow up to 20 alphabetic characters.

从他们的网站:regexp=^[A-Za-z]{1,20}$最多允许 20 个字母字符。

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

请嘿嘿嘿:-D

回答by Cameron

How about:

怎么样:

^[^\*]

Which matches any input that does notstart 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 notone 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
  • 第一个^意思是“在字符串的开头”
  • [...]结构是一个字符类,不匹配的括号中的那些中的单个字符
  • ^在字符类手段的开始“否定字符类”,即匹配的任何字符列出的一个
  • 所述\*指文字*; *在正则表达式中具有特殊含义,所以我用反斜杠对其进行了转义。正如 Rob 在评论中指出的那样,在字符类中转义(大多数)特殊字符并不是绝对必要的

回答by DuckMaestro

How about ^[^\*].+.

怎么样^[^\*].+

Broken down:

分解:

  • ^= start of string.
  • [^\*]= any one character not the '*'.
  • .+= any other character at least once.
  • ^= 字符串的开始。
  • [^\*]= '*' 以外的任何一个字符。
  • .+= 任何其他字符至少一次。

回答by Kamil Szot

You can invert character class by using ^ after [

您可以在 [ 之后使用 ^ 来反转字符类

regexp=[^\u002A]

regexp=[^\u002A]