简体   繁体   中英

How can I use “or”, “and” in C# Regex?

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

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.

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.

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$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM