You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET正则表达式如何关联匹配到的搜索关键词?

在VB.NET中获取正则匹配的触发关键词

有两种简单的方法可以实现你的需求,核心思路是把Sailor和Soldier放到捕获组里,这样就能在匹配结果中直接拿到触发词:

方法一:调整正则结构,直接捕获触发词

把原来的后行断言改成捕获组,修改后的正则表达式如下:

(Sailor|Soldier) (.+?)(?= Bill)
  • 第1个捕获组(Groups(1))会返回匹配到的触发词(Sailor或Soldier)
  • 第2个捕获组(Groups(2))会返回你原本需要的my name is这类内容

在VB.NET中的示例代码:

Dim input1 As String = "hello Sailor my name is Bill"
Dim input2 As String = "hello Soldier my name is Bill"
Dim pattern As String = "(Sailor|Soldier) (.+?)(?= Bill)"

' 处理第一个输入
Dim match1 As Match = Regex.Match(input1, pattern)
If match1.Success Then
    Dim triggerWord As String = match1.Groups(1).Value ' 结果是"Sailor"
    Dim targetContent As String = match1.Groups(2).Value ' 结果是"my name is"
End If

' 处理第二个输入
Dim match2 As Match = Regex.Match(input2, pattern)
If match2.Success Then
    Dim triggerWord As String = match2.Groups(1).Value ' 结果是"Soldier"
    Dim targetContent As String = match2.Groups(2).Value ' 结果是"my name is"
End If

方法二:保留原后行断言,新增捕获组

如果你不想改动原有的后行断言逻辑,可以把触发词嵌套进捕获组里,正则表达式改成:

(?<=((Sailor)|(Soldier)) ).+?(?= Bill)

这种情况下,Groups(1)会返回触发词(Sailor或Soldier),Groups(2)或Groups(3)会对应具体匹配到的词(其中一个有值,另一个为空)。不过这种写法不如第一种直观,推荐优先用方法一。

内容的提问来源于stack exchange,提问作者Ash_stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:06:33