首页 > 解决方案 > 如何查找包含两个数字且它们之间有一个字符的字符串

问题描述

我想找到一个模式,它包含两个正整数,在字符串中它们之间有一个 % 或 - 字符。让我们考虑一个字符串 "Приветственный_3%5" 在这里我们可以从字符串中看到两个数字 3 和 5 之间有一个 % 符号。我想找到包含两个数字的一​​部分的字符串,它们之间有一个 '%' 或 '-' 符号。

标签: c#asp.net

解决方案


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

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.

推荐阅读