c# - 验证由 3-4 个字符后跟分号组成的字符串的正则表达式

标签 c# regex

我想制作一个正则表达式来验证字符串是否采用这种格式:

".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/

相关文章:

java - 检查文本是否有多个链接

Python正则表达式子函数与匹配组

jquery - 替换文本区域中的数字模式和电子邮件

c# - 将数据表拆分为多个固定大小的表

c# - 如何开始开发软件?

c# - 我可以依赖按注册顺序调用的事件处理程序吗?

c# - 新手wpf设计问题

.net - 正则表达式:基于先前捕获组的模式

ruby - 在特定字符后将字符串插入 URL

c# - 有没有办法省略参数?