The Match.Result
method is what you want. See API documentation and documentation on Regex substitution patterns.
Use Regex.Match(input, pattern).Result("$1")
to get what you want.
To give a complete example, here is the unit test I used to confirm that this solution would work:
[Test]
public void TestRegexMatchResult() {
var input = "Other text [name:value] and other text";
var pattern = @"\[name:(\w+)\]";
Assert.AreEqual("value", Regex.Match(input, pattern).Result("$1"));
}
The test passes.
You can also go through a string and extract multiple occurrences of the pattern:
[Test]
public void TestRegexMatchesResult() {
var input = "Some [name:value] pairs [name:something] here.";
var pattern = @"\[name:(\w+)\]";
var results = Regex.Matches(input, pattern).OfType<Match>()
.Select(match => match.Result("$1"));
Assert.AreEqual(2, results.Count());
Assert.AreEqual("value", results.ElementAt(0));
Assert.AreEqual("something", results.ElementAt(1));
}
Finally, if you need to abstract this to something other than "name", you can do this:
[Test]
public void TestMatchingNameAndValue() {
var input = "[key:value] [another_key:some_other_value]";
var pattern = @"\[(\w+):(\w+)\]";
var results = Regex.Matches(input, pattern).OfType<Match>()
.Select(match => new KeyValuePair<string, string>(
match.Result("$1"),
match.Result("$2")));
Assert.AreEqual(2, results.Count());
Assert.AreEqual("key", results.ElementAt(0).Key);
Assert.AreEqual("value", results.ElementAt(0).Value);
Assert.AreEqual("another_key", results.ElementAt(1).Key);
Assert.AreEqual("some_other_value", results.ElementAt(1).Value);
}