如何检查字符串中是否有2个破折号?

时间:2017-08-08 05:12:34

标签: c# visual-studio

我正在尝试检查字符串(textBox1.Text)中是否有2个破折号(例如XXXXX-XXXXX-XXXXX)。我没有学习像Regex这样全新的东西,找不到最好的方法。

现在我有:

else if (!textBox1.Text.Contains("-"))
{
    label3.Text = "Incorrect";
}

但是,这只会检查1个破折号。

基本上,如果字符串textBox1.Text中恰好有2个破折号,我将如何检查if语句?

3 个答案:

答案 0 :(得分:2)

您可以使用Count方法

string input = "XXXXX-XXXXX-XXXXX";

var dashCounter = input.Count(x => x == '-');

然后

if(dashCounter == 2) { }

答案 1 :(得分:2)

正则表达并不是那么复杂,值得学习。

这是使用LINQ的简单解决方案。

int dashCount = textbox1.Text.Count(t=>t =='-');

使用TakeWhile作为另一个建议,这里只会显示前导破折号。例如,要获得2,您需要一个类似--XX-XX的字符串(请注意,非领先的破折号也不会被计算在内)。

答案 2 :(得分:0)

您可以使用以下符号检查字符串中的短划线计数:

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.