C# 如何查找包含两个数字且中间有一个字符的字符串

C# 如何查找包含两个数字且中间有一个字符的字符串,c#,asp.net,C#,Asp.net,我想找到一个模式,它包含两个正整数,在字符串中它们之间有一个%或-字符。让我们来考虑一个字符串,即“5×3”,我们可以从字符串中看到两个数字3和一%,它们之间有一%个符号。我想找到一个字符串,它有两个数字的一部分,中间有“%”或“-”号 创建一个遵循以下步骤的简单函数: 循环抛出整个文本,因为您要检查所有 如果当前字符是数字,则获取完整数字,例如123 在进入第3阶段之前,您需要提取所有 如果%or-是数字后的下一个字符,下一个字符是数字 提取第二个数字 您可以为此使用正则表达式。您甚至可以使用

我想找到一个模式,它包含两个正整数,在字符串中它们之间有一个%或-字符。让我们来考虑一个字符串,即“5×3”,我们可以从字符串中看到两个数字3和一%,它们之间有一%个符号。我想找到一个字符串,它有两个数字的一部分,中间有“%”或“-”号

创建一个遵循以下步骤的简单函数:

  • 循环抛出整个文本,因为您要检查所有
  • 如果当前字符是数字,则获取完整数字,例如123 在进入第3阶段之前,您需要提取所有
  • 如果%or-是数字后的下一个字符,下一个字符是数字
  • 提取第二个数字

  • 您可以为此使用正则表达式。您甚至可以使用正则表达式提取整数值:

    var input = "Приветственный_32%50";
    var searchPattern = @"(\d+)[%-](\d+)";
    
    var matches = Regex.Matches(input, searchPattern);
    
    if (matches.Count == 1) {
    
        // A single occurence of this pattern has been found in the input string.
        // We can extract the numbers from the Groups of this Match.
        // Group 0 is the entire match, groups 1 and 2 are the groups we captured with the parentheses
        var firstNumber = matches[0].Groups[1].Value;
        var secondNumber = matches[0].Groups[2].Value;
    }
    
    正则表达式模式解释:

    (\d+) ==> matches one or more digits and captures it in a group with the parentheses.
    [%-]  ==> matches a single % or - character
    (\d+) ==> matches one or more digits and captures it in a group with the parentheses.
    

    您的“十进制”数字类型是
    int
    还是
    decimal
    ?而且,它们一定是非负的吗?如果您只想检查“无符号整数+分隔符+无符号整数”,我希望一些正则表达式,如
    \d[%-]\d
    它将是正整数,谢谢。