正则表达式,如何提取两个单词之间的字符串

问题描述 投票:0回答:1
string text = "0. Index - 1, Name - mirlan, Balance - 300";

我需要提取整数1作为索引,字符串“mirlan”作为名称,int余额作为300

我需要用正则表达式,正则表达式来做到这一点

第一次尝试:

Regex regexIndex = new Regex(@"Index-[0-9]*,", RegexOptions.IgnorePatternWhitespace);
int index = Convert.ToInt32(regexIndex.Match(text));

第二次尝试:

Regex regexIndex = new Regex(@"Index-[0-9]*,", RegexOptions.IgnorePatternWhitespace);
MatchCollection IndexMatches = regexIndex.Matches(text);
int index = Convert.ToInt32(IndexMatches[0].Value);
c# .net regex
1个回答
0
投票

您可以使用正则表达式分组来提取您需要的值。

示例:

// using System.Text.RegularExpressions;

string text = "0. Index - 1, Name - mirlan, Balance - 300";

string pattern = @"Index - (\d+), Name - (.+)?, Balance - (\d+)";
Match match = Regex.Match(text, pattern);

string index = match.Groups[1].Value;
string name = match.Groups[2].Value;
string balance = match.Groups[3].Value;

Console.WriteLine($"Index: {index}");
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Balance: {balance}");

输出:

Index: 1
Name: mirlan
Balance: 300
© www.soinside.com 2019 - 2024. All rights reserved.