简体   繁体   English

C#正则表达式:如何做一个OR匹配?

[英]c# regex: how to do an OR match?

I want to know how I can pass an OR regex expression. 我想知道如何传递OR正则表达式。 I tried "(u|^upload)" but this doesn't seem to work and instead catches anything I type 我尝试了"(u|^upload)"但这似乎不起作用,而是捕获了我键入的任何内容

  var regex = new Regex("(u|^upload)", RegexOptions.IgnoreCase);
  return regex.IsMatch(msg.Text);

I expect it to catch u or U or upload or Upload 我希望它能抓住你或你或上传或上传

The correct pattern would be: 正确的模式是:

^(u|upload)$

Where ^ and $ are anchors that match the start and end of the string, respectively. 其中^$是分别与字符串的开头和结尾匹配的 This means that the pattern will only match the entire string or nothing at all. 这意味着该模式将仅匹配整个字符串,或者完全不匹配。

But for that matter, you don't really need regular expressions at all: 但是,对于这个问题,你并不需要在所有的正则表达式:

var values = new[] { "u", "upload" };
return values.Contains(msg.Text, StringComparer.OrdinalIgnoreCase);

Just for illustration, an equivalent pattern would be: 仅出于说明目的,等效模式为:

^u(pload)?$

This will mach any string that starts with u , optionally followed by pload , followed by the end of the string. 这将处理以u开头的任意字符串,可以选择后面跟着pload ,然后是字符串的末尾。

Note however, neither of these will just match u , U , upload , or Upload . 但是请注意,这些都不只会匹配uUuploadUpload Thanks to RegexOptions.IgnoreCase , they would also match UPLOAD or uPlOaD . 多亏了RegexOptions.IgnoreCase ,它们也可以匹配UPLOADuPlOaD If you only want to match exactly those four options you could do: 如果只想完全匹配这四个选项,则可以执行以下操作:

var regex = new Regex("^[uU](pload)?$");

Or (using group options ): 或(使用组选项 ):

var regex = new Regex("^u(?-i:pload)?$", RegexOptions.IgnoreCase);

Or without regular expressions: 或不带正则表达式:

var values = new[] { "u", "U", "upload", "Upload" };
return values.Contains(msg.Text);

Test this to match the strings start with 'u' or 'U',and end with 'e' or 'E'.And the charactor 'u' or 'U'. 测试一下以匹配以'u'或'U'开头,以'e'或'E'结尾的字符串以及字符'u'或'U'匹配的字符串。

([uU].*?e)|([uU])

Or you can use this to match 'update' , 'Update' , 'u' and 'U'. 或者,您可以使用它来匹配'update','Update','u'和'U'。

([uU]pdate)|([uU])

To capture both u and U or upload and Upload use this 要同时捕获u和U或上载和上载,请使用此

([uU]|[uU]pload)

If you want it at the beginning of the string: 如果您希望在字符串的开头:

^([uU]|[uU]pload)

If you want this to be checked against the entire string use: 如果要针对整个字符串进行检查,请使用:

^([uU]|[uU]pload)$

Demo here 在这里演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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