我想制作一个正则表达式来验证字符串是否采用这种格式:
".xml;.mp4;.webm;.wmv;.ogg"
文件格式以分号分隔。
最好的方法是什么?
最佳答案
我们可以尝试使用模式 ^(?:\.[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
旁注:我在括号内的术语内使用了 ?:
,理论上应该告诉正则表达式引擎不捕获这些术语。这可能会提高性能,但代价可能是模式的可读性稍差。
关于c# - 验证由 3-4 个字符后跟分号组成的字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53912921/