I’ve never been able to construct a regular expression on my own, and now I have a simple application that needs one. How do I construct a simple regex that matches:
- A fixed string
- No whitespace / any whitespace
- The ‘=’ char
- No whitespace / any whitespace
- The ‘(‘ char
Currently I’m using the following code to match whole words, but as you can see its quite limited in its functionality.
Regex.Matches(data, @"\b" + Regex.Escape(columnID + "=(") + @"\b");
Regex.Matches(data, @"\b" + Regex.Escape(columnID + "= (") + @"\b");
Regex.Matches(data, @"\b" + Regex.Escape(columnID + " =(") + @"\b");
Regex.Matches(data, @"\b" + Regex.Escape(columnID + " = (") + @"\b");
“any” in regex means the
*quantifier (“Kleene star”), which exactly means “the previous token, arbitrarily often”.Note that for this to work you obviously can escape only the fixed word, not the rest.
Also note that we now had to escape the opening parenthesis at the end by hand.
And, as Hans noted correctly in the comments, it’s common to use
\sinstead of the space;\sstands for “whitespace”, which includes conventional spaces, tabs and newline characters.