C# 在C中使用正则表达式捕获字符串中的数值#

C# 在C中使用正则表达式捕获字符串中的数值#,c#,.net,regex,C#,.net,Regex,我有一个字符串,其中包含0个或更多出现的ABC=dddddd。dddd表示整数值,不一定是四位数字 我想做的是捕获这个模式中出现的整数值。我知道如何使用正则表达式执行匹配,但我对捕获是新手。不必在一次调用中捕获所有ABC整数值,可以在字符串上循环 如果这太复杂了,我将只编写一个小型解析器,但如果它相当优雅的话,我想使用正则表达式。非常感谢您的专业知识。您可以使用以下内容: MatchCollection allMatchResults = null; try { // This matc

我有一个字符串,其中包含0个或更多出现的
ABC=dddddd
dddd
表示整数值,不一定是四位数字

我想做的是捕获这个模式中出现的整数值。我知道如何使用正则表达式执行匹配,但我对捕获是新手。不必在一次调用中捕获所有ABC整数值,可以在字符串上循环


如果这太复杂了,我将只编写一个小型解析器,但如果它相当优雅的话,我想使用正则表达式。非常感谢您的专业知识。

您可以使用以下内容:

MatchCollection allMatchResults = null;
try {
    // This matches a literal '=' and then any number of digits following
    Regex regexObj = new Regex(@"=(\d+)");
    allMatchResults = regexObj.Matches(subjectString);
    if (allMatchResults.Count > 0) {
        // Access individual matches using allMatchResults.Item[]
    } else {
        // Match attempt failed
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
根据你的情况,也许这更符合你的要求:

try {
    Regex regexObj = new Regex(@"=(\d+)");
    Match matchResults = regexObj.Match(subjectString);
    while (matchResults.Success) {
        for (int i = 1; i < matchResults.Groups.Count; i++) {
            Group groupObj = matchResults.Groups[i];
            if (groupObj.Success) {
                // matched text: groupObj.Value
                // match start: groupObj.Index
                // match length: groupObj.Length
            } 
        }
        matchResults = matchResults.NextMatch();
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
试试看{
Regex regexObj=新的Regex(@“=(\d+));
Match matchResults=regexObj.Match(subjectString);
while(matchResults.Success){
对于(int i=1;i
首先,我们需要从一个与我们正在寻找的模式匹配的正则表达式开始。这将与您给出的示例相匹配(假设ABC是字母数字):
\w+\s*=\s*\d+

接下来,我们需要通过定义捕获组来定义要在匹配中捕获的内容。Net包括对命名捕获组的支持,这是我绝对喜欢的。我们使用
(?表达式)
指定一个组,将正则表达式转换为:
(?\w+)\s*=\s*(?\d+)
。这给了我们两个捕获,关键和价值

使用此选项,我们可以迭代文本中的所有匹配项:

Regex pattern = new Regex(@"(?<key>\w+)\s*=\s*(?<value>\d+)");
string body = "This is your text here.  value = 1234";
foreach (Match match in pattern.Matches(body))
{
    Console.WriteLine("Found key {0} with value {1}", 
        match.Groups.Item["key"].Value, 
        match.Groups.Item["value"].Value
    );
}
Regex模式=新的Regex(@“(?\w+)\s*=\s*(?\d+);
string body=“这里是您的文本。value=1234”;
foreach(模式匹配。匹配(主体))
{
WriteLine(“找到值为{1}的键{0}”,
匹配.Groups.Item[“key”]值,
匹配.Groups.Item[“value”].value
);
}

谢谢,但我知道如何进行常规比赛(见问题);我想使用.NET正则表达式的捕获功能。