C# 验证字符串的正则表达式由3-4个字符和分号组成
我想制作一个用于验证字符串的正则表达式,其格式如下:C# 验证字符串的正则表达式由3-4个字符和分号组成,c#,regex,C#,Regex,我想制作一个用于验证字符串的正则表达式,其格式如下: ".xml;.mp4;.webm;.wmv;.ogg" 文件格式以分号分隔 ^(?:\.[a-zA-Z0-9]+;)*\.[a-zA-Z0-9]+$ 最好的方法是什么?我们可以尝试使用模式^(?:\.[A-Za-z0-9]{3,4})(?:;\.[A-Za-z0-9]{3,4})*$: Regex regex = new Regex(@"^(?:\.[A-Za-z0-9]{3,4})(?:;\.[A-Za-z0-9]{3,4})*$");
".xml;.mp4;.webm;.wmv;.ogg"
文件格式以分号分隔
^(?:\.[a-zA-Z0-9]+;)*\.[a-zA-Z0-9]+$
最好的方法是什么?我们可以尝试使用模式
^(?:\.[A-Za-z0-9]{3,4})(?:;\.[A-Za-z0-9]{3,4})*$
:
Regex regex = new Regex(@"^(?:\.[A-Za-z0-9]{3,4})(?:;\.[A-Za-z0-9]{3,4})*$");
Match match = regex.Match(".xml;.mp4;.webm;.wmv;.ogg");
if (match.Success)
{
Console.WriteLine("MATCH");
}
说明:
^ from the start of the string
(?:\.[A-Za-z0-9]{3,4}) match a dot followed by 3-4 alphanumeric characters
(?:;\.[A-Za-z0-9]{3,4})* then match semicolon, followed by dot and 3-4 alphanumeric
characters, that quantity zero or more times
$ match the end of the string
旁注:我在括号中的术语中使用了
?:
,理论上应该告诉正则表达式引擎不要捕获这些术语。这可能会提高性能,但可能是以模式的可读性稍差为代价。类似于这样的内容,但只需要检查一种格式(如果列表只有一种格式,则后面会有分号)
最好的方法是写一个正则表达式,如果你在写一篇文章时遇到困难的话。