I have a pattern to match with the string: string pattern = @"asc" I am checking the SQL SELECT query for right syntax, semantics, ... I need to say that in the end of the query string I can have "asc" or "desc". How can it be written in C#?
You want the "alternation" operator, which is the pipe.
For instance, I believe this would be represented as:
asc|desc
If you want to make it a non-capturing group you can do it in the normal way. I'm not a regex expert, but that's the first thing to try.
EDIT: MSDN has a page about regular expression language elements which may help you.
That'd look like
new Regex("asc$|desc$").IsMatch(yourQuery)
assuming that you're mandating that asc/desc is the end of the query. You could also do (?:asc|desc)$
which is a little cleaner with the single $
, but less readable.
Just to add to the other answers, you probably wanna apply an ignore case option to the regex as well.
string tempString = "SELECT * FROM MyTable ORDER BY column DESC";
Regex r = new Regex("asc$|desc$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
bool answer = r.IsMatch(tempString);
I reckon something like the following works as a regex in .Net:
asc|desc\z
.. it will match end of line as well as end of string. If you just want end of string try:
asc|desc$