简体   繁体   English

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

[英]How do I check that a string has 2 dashes in it?

I am attempting to check that a string ( textBox1.Text ) has 2 dashes in it (eg XXXXX-XXXXX-XXXXX). 我正在尝试检查字符串( textBox1.Text )中是否包含2个破折号(例如XXXXX-XXXXX-XXXXX)。 I've had trouble figuring out the best way to do this without learning a whole new thing like Regex. 我在不学习像Regex这样的全新事物的情况下找出最佳方法的麻烦。

Right now I have: 现在我有:

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

However, this only checks for 1 dash. 但是,这仅检查1个破折号。

Basically, how would I have an if statement check if string textBox1.Text has exactly 2 dashes in it? 基本上,我将如何通过if语句检查字符串textBox1.Text是否恰好有2个破折号?

You can use the Count method 您可以使用Count方法

string input = "XXXXX-XXXXX-XXXXX";

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

then 然后

if(dashCounter == 2) { }

Regex isn't really all that complicated, it's worth learning. 正则表达式实际上并没有那么复杂,值得学习。

Here's a simple solution using LINQ. 这是使用LINQ的简单解决方案。

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

Using TakeWhile as another suggested here will only show you the leading dashes . 在此处建议使用TakeWhile作为另一个建议,只会向您显示前划线 For example, to get 2 , you would need a string like --XX-XX (note that non-leading dashes wont be counted either). 例如,要获得2 ,您将需要一个--XX-XX类的字符串(请注意,也不会计算非前导破折号)。

You can check the count of dashes in a string with: 您可以使用以下命令检查字符串中的破折号:

if str.Count(x => x == '-') != 2 { ... }

This basically means "count the number of items (characters) in the string when said item is equal to a dash". 这基本上意味着“计数当字符串等于破折号时字符串中的条目(字符)数”。 Checking it against two will allow you to detect the validity or otherwise of your input string. 对照两个进行检查,可以检测输入字符串的有效性或其他有效性。


If you were up to learning regular expressions, this is as good a place as any to start. 如果你多达学习正则表达式,这是一个很好的地方一样开始。 You could check for a specific pattern with something like: 您可以使用以下方法检查特定的模式:

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);
        }
    }
}

Now that regex may look complicated but it's relatively simple: 现在,正则表达式可能看起来很复杂,但是相对来说很简单:

^       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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM