如何在带问号通配符的OCR字符串中查找目标子串并获取其索引
解决方案
你要的匹配规则可以通过正则表达式快速实现,核心逻辑是把搜索文本的每个字符转换为「匹配自身或匹配问号」的正则原子规则,再用.NET内置的正则类获取匹配位置即可。
完整实现代码
Imports System.Text.RegularExpressions ' 业务代码部分 Dim resultIndex As Integer = -1 Dim LargeOcrText As String = "fAsD ?GjSDFpG HjDYA?C JLgD FHaYsV MKiI?oL XgXj?GN sHVKgG?" Dim searchText As String = "ABC" ' 构造正则模式:每个搜索字符对应 [字符?] 的匹配规则 Dim pattern As String = String.Join("", searchText.Select(Function(c) $"[{Regex.Escape(c.ToString())}\?]")) Dim match As Match = Regex.Match(LargeOcrText, pattern) If match.Success Then resultIndex = match.Index End If ' 执行后resultIndex的值即为预期的18
代码说明
- 构造模式时用
Regex.Escape处理搜索文本中可能存在的正则特殊字符(比如$、^这类),避免匹配出错 Match.Index属性直接返回匹配结果在原字符串中的起始索引,符合需求- 如果需要找所有匹配的位置,把
Regex.Match换成Regex.Matches遍历所有匹配结果即可
非正则实现方案(可选)
如果不想依赖正则,也可以手动遍历原串逐个位置验证匹配:
Dim resultIndex As Integer = -1 Dim LargeOcrText As String = "fAsD ?GjSDFpG HjDYA?C JLgD FHaYsV MKiI?oL XgXj?GN sHVKgG?" Dim searchText As String = "ABC" Dim searchLen As Integer = searchText.Length Dim textLen As Integer = LargeOcrText.Length If searchLen <= textLen Then For i As Integer = 0 To textLen - searchLen Dim isMatch As Boolean = True For j As Integer = 0 To searchLen - 1 If LargeOcrText(i + j) <> "?"c AndAlso LargeOcrText(i + j) <> searchText(j) Then isMatch = False Exit For End If Next If isMatch Then resultIndex = i Exit For End If Next End If
该方案逻辑更直观,不需要掌握正则知识,性能对于普通长度的OCR文本完全够用。
内容的提问来源于stack exchange,提问作者Odin Sonnah
相关产品推荐
相关产品推荐

