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.
[^+]
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}
Or, as FailedDev pointed out, ?
works too:
[^+]?
As expected, testing with Chrome's JavaScript console shows no match for "+"
but does match other characters:
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 +
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.