您可以检查破折号的计数与字符串:
if str.Count(x => x == '-') != 2 { ... }
这基本上意味着“数项的字符串中(字符)的数量时说,产品等于几许”。检查它与两个将允许您检测您的输入字符串的有效性或其他。
如果是高达学习正则表达式,这是一个很好的地方一样开始。你可以检查特定模式的东西,如:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "XXXXX-XXXXX-XXXXX";
Regex re = new Regex(@"^[^-]*-[^-]*-[^-]*$");
Console.Out.WriteLine(re.Match(str).Success);
}
}
}
现在正则表达式可以看复杂,但它是比较简单的:
^ Start anchor.
[^-]* Zero or more of any non-dash characters.
- Dash character.
[^-]* Zero or more of any non-dash characters.
- Dash character.
[^-]* Zero or more of any non-dash characters.
$ End anchor.
这是唯一一个似乎工作,谢谢! – XantiuM