字符串索引验证

时间:2016-03-27 12:19:47

标签: c# string parsing indexing

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

3 个答案:

答案 0 :(得分:3)

如果您的预期输入始终为wx-yz类型,其中w,x,y,z为数字。 您可以检查字符串是否包含特殊字符。 然后你可以拆分字符串并检查每个部分是否是数字。如果是数字,您可以进一步检查它是否属于某个特定范围或根据需要进行其他验证。 如果一切都符合预期,请进行进一步处理。

    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
   }

答案 1 :(得分:2)

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

答案 2 :(得分:2)

这是一个更简单的Regex

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

        }
    }
}