要在匹配后访问命名捕获组的内容,您需要使用正则表达式对象:
Dim RegexObj As New Regex("(?<quote>['""])(?<text>.*?)\k<quote>")
Result = RegexObj.Match(Subject).Groups("text").Value
现在Result
将包含(?<text>...)
捕获组的内容。
对于多个匹配,您可以遍历结果,调用.NextMatch()
直到找到最后一个匹配:
Dim ResultList As StringCollection = New StringCollection()
Dim RegexObj As New Regex("(?<quote>['""])(?<text>.*?)\k<quote>")
Dim Result As Match = RegexObj.Match(Subject)
While MatchResult.Success
ResultList.Add(Result.Groups("text").Value)
Result = Result.NextMatch()
End While
问题的原始答案(关于反向引用,而不是捕获组):
有两种情况可以使用反向引用:
- 要在同一个正则表达式中引用反向引用,请使用
\k<groupname>
.
- 要在替换文本中插入与命名组匹配的文本,请使用
${groupname}
.
例如,
res = Regex.Replace(subject, "(?<quote>['""])(?<text>.*?)\k<quote>", "*${text}*")
将改变
This is a "quoted text" and 'so is this'!
进入
This is a *quoted text* and *so is this*!