我也遇到了这个问题,我通过在Match对象上创建一些扩展方法来解决它,以替换较大匹配值中命名组匹配值的值。在这个例子中,我想替换"id"组的值,而不必担心周围的垃圾代码:
Dim contents = Regex.Replace(contents, "\|(?'id'\d+)\r\n",
Function(m As Match)
Return m.ReplaceGroupValue("id", "[REPLACEMENT VALUE]")
End Function)
使用以下内容:
<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
如果替换值实际上是要被替换的值的更复杂函数,那么使用这种形式会更方便:
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
ReplaceGroupValue函数替换较大匹配表达式中的组值,因此您可以专注于要处理的命名组。