[英]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". 我有一个与字符串匹配的模式:字符串模式= @“ asc”我正在检查SQL SELECT查询的正确语法,语义,...我需要说的是,在查询字符串的末尾我可以有“ asc” ”或“ desc”。 How can it be written in C#?
如何用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. 假设您要强制asc / desc是查询的结尾。 You could also do
(?:asc|desc)$
which is a little cleaner with the single $
, but less readable. 你也可以做
(?:asc|desc)$
这是一个小吸尘器单$
,但不可读性。
You want the "alternation" operator, which is the pipe. 您需要“ alternation”运算符,即管道。
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. 编辑:MSDN有一个关于正则表达式语言元素的页面,可能会对您有所帮助。
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: 我认为,.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$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.