繁体   English   中英

如何查找包含两个数字且它们之间有一个字符的字符串

[英]How to find string which contains two numbers with a character between them

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

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

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.

创建一个简单的 function 遵循这些步骤:

  1. 循环抛出整个文本,因为你想检查所有
  2. 如果当前字符是一个数字,则获取完整的数字,例如 123,您需要在传递到第 3 阶段之前提取所有字符。
  3. 如果 % 或 - 是数字之后的下一个字符并且下一个字符是数字
  4. 提取第二个数字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM