【问题标题】:How to add numbers in a mixed string C#如何在混合字符串中添加数字C#
【发布时间】:2019-07-08 17:17:37
【问题描述】:

示例 = "I-000146.22.43.24"

在示例中,我需要验证句点后的最后一个数字是否超过 9。目前是 24,这是无效的。 01-08 有效,除此之外的任何内容都无效。

如何添加逻辑来检查这一点?

【问题讨论】:

  • 尝试以下操作:字符串示例 = "I-000146.22.43.24"; int lastPeriod = example.LastIndexOf(".");字符串 lastNumberStr = example.Substring(lastPeriod + 1); int lastNumber = int.Parse(lastNumberStr);
  • 上一个句号之后你能有两个以上的数字吗?

标签: c# .net


【解决方案1】:

一种解决方案是使用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.

【讨论】:

  • 我喜欢强大的RegexOptions.RightToLeft :) 另外,^.+ 在你的模式中只是浪费时间。
  • @NetMage 你是对的。我将其保留为占位符,以防 OP 想要以某种方式验证字符串的第一部分但最终没有在答案中提及。
【解决方案2】:

你可以使用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

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2017-08-31
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多