Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not getting all my regex captures?

Tags:

c#

.net

regex

I am using .NET's Regex to capture information from a string. I have a pattern of numbers enclosed in bar characters, and I want to pick out the numbers. Here's my code:

string testStr = "|12||13||14|";
var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$");

However, testMatch.Captures only has 1 entry, which is equal to the whole string. Why doesn't it have 3 entries, 12, 13, and 14? What am I missing?

like image 985
Jez Avatar asked Apr 30 '14 17:04

Jez


People also ask

How do I get everything in regular expressions?

Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.

How do you repeat a capturing group in regex?

"Capturing a repeated group captures all iterations." In your regex101 try to replace your regex with (\w+),? and it will give you the same result. The key here is the g flag which repeats your pattern to match into multiple groups.

What does \\ mean in regex?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.


1 Answers

You want to use the Captures property on the Group itself - in this case testMatch.Groups[1]. This is needed since there could be multiple capture groups in the regex, and there would be no way for it to know which one you are referring to.

Using testMatch.Captures effectively gives testMatch.Groups[0].Captures.

This works for me:

string testStr = "|12||13||14|";
var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$");

int captureCtr = 0;
foreach (Capture capture in testMatch.Groups[1].Captures) 
{
    Console.WriteLine("Capture {0}: {1}", captureCtr++, capture.Value);
}

Reference: Group.Captures

like image 185
NullUserException Avatar answered Oct 12 '22 09:10

NullUserException