c# - 如何查找包含两个数字且它们之间有一个字符的字符串
问题描述
我想找到一个模式,它包含两个正整数,在字符串中它们之间有一个 % 或 - 字符。让我们考虑一个字符串 "Приветственный_3%5" 在这里我们可以从字符串中看到两个数字 3 和 5 之间有一个 % 符号。我想找到包含两个数字的一部分的字符串,它们之间有一个 '%' 或 '-' 符号。
解决方案
您可以为此使用正则表达式。您甚至可以使用 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.
推荐阅读
- r - 如何使用我的代码从网页中提取固有链接(错误:下标越界)?
- swift - 从函数内的各种循环中返回一个值
- sql - SQL 查询总和(CASE、WHEN、ELSE)
- ios - Xcode 未在 iPA 中捆绑所有启动图像
- javascript - 需要在非 es6-javascript 字符串中提取间接定义的变量名称的基于正则表达式的方法
- sql-server - 使用 onguard 系统访问控制数据库为夜班工作人员提供的时间
- javascript - 如何从外部链接打开 bootstrap 3 选项卡?
- jquery - 在 JQuery POST 方法中添加 DataType 属性
- react-native - “react-native init project”命令不起作用
- c - 为什么 itoa 被声明为不安全?