I've also had this problem and I addressed it by creating some extension methods on the Match object to replace the value of the named group match value within the larger match value. In this example, I want to replace the value of the "id" group, without having to worry about the surrounding junk:
Dim contents = Regex.Replace(contents, "\|(?'id'\d+)\r\n",
Function(m As Match)
Return m.ReplaceGroupValue("id", "[REPLACEMENT VALUE]")
End Function)
which uses:
<Extension()> _
Function ReplaceGroupValue(ByVal m As Match, ByVal sGroupName$, ByVal sNewValue$) As String
'get the value of the specified group
Dim value = m.Groups(sGroupName).Value
Return m.Value.Replace(value, sNewValue)
End Function
If the replacement value is actually a more complicated function of the value to be replaced, it's more convenient to use this form:
Dim contents = Regex.Replace(contents, "\|(?'id'\d+)\r\n",
Function(m As Match)
Return m.ReplaceGroupValue("id", Function(id) [do something with the id])
End Function)
<Extension()> _
Function ReplaceGroupValue(ByVal m As Match, ByVal sGroupName$, ByVal callback As Func(Of String, String)) As String
'get the value of the specified group
Dim value = m.Groups(sGroupName).Value
Return m.Value.Replace(value, callback(value))
End Function
The ReplaceGroupValue function replaces the group value within the larger match expression, so you can concentrate on the named group that you want to work with.