tags:

views:

382

answers:

4

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#?

+1  A: 

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.

Jon Skeet
+4  A: 

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.

bdukes
+1  A: 

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);
Eoin Campbell
A: 

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$
ip