2017-08-08 99 views
0

我试图检查一个字符串(textBox1.Text)中有2个破折号(例如XXXXX-XXXXX-XXXXX)。如果不学习像Regex这样的全新方法,我很难找出最好的方法来做到这一点。如何检查一个字符串中有2个破折号?

现在我有:

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

1个破折号然而,这仅仅检查。

基本上,我将如何有一个if语句检查字符串textBox1.Text是否恰好有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. 
+0

这是唯一一个似乎工作,谢谢! – XantiuM

2

可以使用Count方法

string input = "XXXXX-XXXXX-XXXXX"; 

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

然后

if(dashCounter == 2) { } 
+1

呃....你确定吗?我得到0 ... – john

+1

'string code = textBox1.Text; var dashCounter = code.TakeWhile(x => x ==' - ')。Count();'then'else if(dashCounter == 2){。 ..}似乎不起作用。 – XantiuM

+0

计数法就够了! –

2

正则表达式是不是真的那么复杂,这是值得我们学习。

下面是一个简单的使用LINQ的解决方案。

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

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

相关问题