简体   繁体   English

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

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

I am having a bit of trouble with one part of a regular expression that will be used in JavaScript. 我在JavaScript中使用的正则表达式的一部分遇到了一些麻烦。 I need a way to match any character other than the + character, an empty string should also match. 我需要一种方法来匹配+字符以外的任何字符,空字符串也应该匹配。

[^+] 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 + . 我试过[^+]*思考:“除了+ ,零次或多次以外的任何字符”,但这匹配包括+在内的所有内容。

  • [^+] 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 + . [^+]*表示“匹配任何数量不是+的字符” - 这几乎看起来像我想要的那样,但如果第一个字符(甚至所有字符)都是+ ,它将匹配零个字符。

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

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, ? 或者,正如FailedDev指出的那样, ? works too: 也有效:

[^+]?

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"]

If you're just testing the string to see if it doesn't contain a + , then you should use: 如果您只是测试字符串以查看它是否包含+ ,那么您应该使用:

^[^+]*$

This will match only if the ENTIRE string has no + . 仅当ENTIRE字符串没有+才会匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM