C# 字符串索引验证

C# 字符串索引验证,c#,string,parsing,indexing,C#,String,Parsing,Indexing,有人能解释一下如何验证字符串的每个字段吗?字符串“45-78”。我想验证字符串的前两个和最后两个字段(如果它们有所需的数字),以及中间的一个字段(如果它有某种类型的char(-)。有没有这样的方法来验证字符串?如果有人能给我举个简单的例子吗?谢谢大家 如果预期输入的类型始终为wx yz其中w,x,y,z为数字。 using System; using System.Text.RegularExpressions; class Program { static void Main()

有人能解释一下如何验证字符串的每个字段吗?字符串“45-78”。我想验证字符串的前两个和最后两个字段(如果它们有所需的数字),以及中间的一个字段(如果它有某种类型的char(-)。有没有这样的方法来验证字符串?如果有人能给我举个简单的例子吗?谢谢大家

如果预期输入的类型始终为
wx yz
其中w,x,y,z为数字。
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        Regex regex = new Regex(@"^[0-9]{2}-[0-9]{2}$");
        Match match = regex.Match("45-55");
        if (match.Success)
        {
            Console.WriteLine("Verified");
        }
    }
}
您可以检查字符串是否包含特殊字符。 然后可以拆分字符串并检查每个部分是否为数字。如果它是数字,您可以进一步检查它是否属于某个特定范围,或者根据需要执行其他验证。 如果一切正常,请进行进一步处理

    string input = "45-78";
    if(input.Contains("-"))
    {
        // the string contains the special character which separates our two number values
        string firstPart = input.Split('-')[0]; // now we have "45" 
        string secondPart = input.Split('-')[1]; // now we have "78"
        int firstNumber;
        bool isFirstPartInt = Int32.TryParse(firstPart, out firstNumber);
        bool isResultValid = true;
        if(isFirstPartInt)
        {
            //check for the range to which the firstNumber should belong
        }
        else isResultValid = false;    

        int secondNumber;
        bool isFirstPartInt = Int32.TryParse(secondPart, out secondNumber);
        if(isFirstPartInt)
        {
            //check for the range to which the secondNumber should belong
        }
        else isResultValid = false;    

        if(isResultValid)
        {
           // string was in correct format and both the numbers are as expected.
           // proceed with further processing
        } 
    }

   else
   {
       // the input string is not in correct format
   }

这里有一个更简单的正则表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "45-78";
            string pattern = @"\d+-\d+";

            Boolean match = Regex.IsMatch(input, pattern);

        }
    }
}

您的字符串是否总是采用
xx-yy
格式?这里的Regex和示例:正如@Fruchtzwerg所提到的,正则表达式可以做到这一点,这就是它们的用途。您也可以通过自定义方法实现同样的效果,例如通过
-
拆分,使用
Int32.TryParse
等。更多代码,但可读性也更高。ihimv。非常感谢您的回复。很好的解释!这就是我想做的。谢谢=)