Steve
Steve

Reputation: 26124

Regex Named Capture for multiple numbers in string

Given a string

 var testData = "1234 test string 987 more test";

I want to be able to use a regex to pull out 1234 and 987. As far as I could tell using

 var reg = new Regex(@"?<numbers>\d+");

should do what I want but when I say

 var match = reg.match(testData);

I would think that

 Assert.AreEqual(match.Groups["numbers"].Captures.Count(), 2);

but it's only 1. What am I doing wrong? Intuition tells me that the

 ?<group> 

means there can only be 0 or 1 of these values. Should I not be using a named group?

 *<group> 

doesn't seem to work in the regex builder in visual studio but I did not try it in my tests.

Upvotes: 3

Views: 2192

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98901

try {
    Regex regexObj = new Regex(@"([\d]+)", RegexOptions.IgnoreCase);
    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
}

Upvotes: -1

Tu Tran
Tu Tran

Reputation: 1977

Why didn't you use the pattern string as below:

Regex reg = new Regex(@"\d+");

and then get the numbers by:

MatchCollection matches = reg.Matches(testData);

After that, the matches variable contains 2 Match value which represent for 1234 and 987.

You also use the assert as:

Assert.AreEqual(matches.Count, 2);

Hope it will help you!

Upvotes: 2

Related Questions