【问题标题】:String index verification字符串索引验证
【发布时间】:2016-03-27 12:19:47
【问题描述】:

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

【问题讨论】:

  • 你的字符串是否一直有xx-yy格式?
  • 正则表达式和示例:msdn.microsoft.com/de-de/library/…
  • 正如@Fruchtzwerg 提到的,正则表达式可以做到这一点,这就是它们的目的。您也可以使用自定义方法实现相同的目的,例如按- 分割,使用Int32.TryParse 等。更多代码,但也更易读。

标签: c# string parsing indexing


【解决方案1】:

如果您的预期输入始终是 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
   }

【讨论】:

  • ihimv。非常感谢你的回复。很好的解释!这就是我想做的。谢谢=)
【解决方案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");
        }
    }
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-21
      • 2022-12-14
      • 2011-02-21
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 2011-11-20
      相关资源
      最近更新 更多