Javascript 正则表达式 - 匹配除 + 之外的任何字符,也应匹配空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8189355/
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-24 05:01:46  来源:igfitidea点击:

Regular Expression - Match any character except +, empty string should also be matched

javascriptregex

提问by zaq

I am having a bit of trouble with one part of a regular expression that will be used in JavaScript. I need a way to match any character other than the +character, an empty string should also match.

我在 JavaScript 中使用的正则表达式的一部分遇到了一些麻烦。我需要一种方法来匹配字符以外的任何+字符,空字符串也应该匹配。

[^+]is almost what I want except it does not match an empty string. I have tried [^+]*thinking: "any character other than +, zero or more times", but this matches everything including +.

[^+]几乎是我想要的,除了它不匹配空字符串。我试过[^+]*想:“除+0 次或多次以外的任何字符”,但这与包括+.

回答by chown

Add a {0,1} to it so that it will only match zero or one times, no more no less:

添加一个 {0,1} 到它,这样它只会匹配零次或一次,不多不少:

[^+]{0,1}

Or, as FailedDev pointed out, ?works too:

或者,正如 FailedDev 指出的那样,?也可以:

[^+]?

As expected, testing with Chrome's JavaScript console shows no match for "+"but does match other characters:

正如预期的那样,使用 Chrome 的 JavaScript 控制台测试显示不匹配"+"但匹配其他字符:

x = "+"
y = "A"

x.match(/[^+]{0,1}/)
[""]

y.match(/[^+]{0,1}/)
["A"]

x.match(/[^+]?/)
[""]

y.match(/[^+]?/)
["A"]

回答by Code Jockey

  • [^+]means "match any single character that is not a +"
  • [^+]*means "match any number of characters that are not a +" - which almost seems like what I think you want, except that it will match zero characters if the first character (or even all of the characters) are +.
  • [^+]意思是“匹配任何不是+”的单个字符
  • [^+]*意思是“匹配任意数量的不是 a 的字符+” - 这几乎看起来像我认为你想要的,除了如果第一个字符(甚至所有字符)是+.

use anchors to make sure that the expression validates the ENTIRE STRING:

使用锚点来确保表达式验证整个字符串:

^[^+]*$

means:

方法:

^       # assert at the beginning of the string
[^+]*   # any character that is not '+', zero or more times
$       # assert at the end of the string

回答by Scott Rippey

If you're just testing the string to see if it doesn't contain a +, then you should use:

如果您只是测试字符串以查看它是否不包含 a +,那么您应该使用:

^[^+]*$

This will match only if the ENTIRE string has no +.

仅当 ENTIRE 字符串没有+.