如何在混合字符串C#中添加数字

时间:2019-07-08 17:17:37

标签: c# .net

example =“ I-000146.22.43.24”

在此示例中,我需要验证句点之后的最后一个数字是否不超过9。当前为24,并且那是无效的。 01-08有效,超出该范围的任何内容。

如何添加逻辑以对此进行检查?

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用Regex。 regex模式将如下所示:

^.+\.(0?[0-8])$

Regex demo

C#示例:

string pattern = @"^.+\.(0?[0-8])$";
string[] inputs = new [] { "I-000146.22.43.24", "I-000146.22.43.09", 
                           "I-000146.22.43.08", "xxxxxxx.07" };
foreach (string input in inputs)
{
    Match match = Regex.Match(input, pattern);
    if (match.Success)
        Console.WriteLine($"The input is valid. Last number is '{match.Groups[1].Value}'.");
    else
        Console.WriteLine("The input is not valid.");
}

输出:

The input is not valid.
The input is not valid.
The input is valid. Last number is '08'.
The input is valid. Last number is '07'.

Try it online

答案 1 :(得分:0)

您可以使用Linq

using System;
using System.Linq;

class MainClass {
    public static void Main (string[] args) {
        String[] tests = new string[3] {"I-000146.22.43.24", "I-000146.22.43.9", "I-000146.22.43.a"};
        foreach (string test in tests) {
            Console.WriteLine ($"{test} is a valid string: {isValidString (test)}");
        }
    }

    private static bool isValidString (string str) {
        var lastNumString = str.Split ('.').Last();
        return isSingleDigit (lastNumString);
    }

    private static bool isSingleDigit (string numString) {
        int number;
        bool success = Int32.TryParse (numString, out number);
        if (success) {
            return number >= 0 && number <= 9;
        }
        return success;
    }
}

输出:

I-000146.22.43.24 is a valid string: False
I-000146.22.43.9 is a valid string: True
I-000146.22.43.a is a valid string: False