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?
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.
"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.
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.
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.
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);
}
Group.Captures
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With