您可以檢查破折號的計數與字符串:
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