Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 +.

like image 632
zaq Avatar asked Nov 18 '11 21:11

zaq


People also ask

Does empty regex match everything?

An empty regular expression matches everything.

Can an empty set be in a regular expression?

∅, the empty set, is a regular expression. ∅ represent the language with no elements {}.

How do you match a blank line in regex?

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.

What is the regular expression is used to match any single character except new line character?

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.


2 Answers

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"] 
like image 181
chown Avatar answered Sep 19 '22 17:09

chown


  • [^+] 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 
like image 34
Code Jockey Avatar answered Sep 19 '22 17:09

Code Jockey