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 +
.
An empty regular expression matches everything.
∅, the empty set, is a regular expression. ∅ represent the language with no elements {}.
The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string.
A period (.) matches any character except a newline character. You can repeat expressions with an asterisk or plus sign. A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression.
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"]
[^+]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With