我可以使用正则表达式,Like运算符和/或Instr()在较大的字符串中找到模式的索引吗?

问题描述 投票:0回答:2

我有一个很大的列表(一个字段一个表),这些列表是从管理不善的旧数据库中导入的非标准化字符串。我需要提取在每个字符串中只出现一次的单位数字(由空格包围)(尽管有时字符串也具有其他的多位数)。例如,从以下字符串:

"Quality Assurance File System And Records Retention Johnson, R.M. 004 4 2999 ss/ds/free ReviewMo = Aug Effective 1/31/2012 FileOpen-?"

我想提取数字4(或字符串中4的位置,即71)

我可以使用

WHERE rsLegacyList.F1 LIKE "* # *" 

select语句中以查找if,每个字符串都有一个单独的数字,从而过滤我的列表。但这并没有告诉我where数字,因此我可以提取数字本身(使用mid()函数)并开始对列表进行排序。目标是用该数字本身创建第二个字段,作为对第一个字段中的较大字符串进行排序的方法。

是否可以将Instr()与正则表达式一起使用,以查找大字符串中正则表达式的位置?像

之类的东西
intMarkerLocation = instr(rsLegacyList.F1, Like "* # *")

但是那确实有效吗?

我感谢所有可以完全避免问题的建议或解决方法。


@ Lee Mac,我制作了一个函数RegExFindStringIndex,如下所示:

Public Function RegExFindStringIndex(strToSearch As String, strPatternToMatch As String) As Integer

    Dim regex                       As RegExp
    Dim Matching                    As Match

    Set regex = New RegExp

    With regex
        .MultiLine = False
        .Global = True
        .IgnoreCase = False
        .Pattern = strPatternToMatch
        Matching = .Execute(strToSearch)
        RegExFindStringIndex = Matching.FirstIndex
    End With

    Set regex = Nothing
    Set Matching = Nothing
End Function

但是它给我一个错误无效使用属性在行Matching = .Execute(strToSearch)

regex ms-access access-vba string-operations instr
2个回答
0
投票

怎么样:

select
    instr(rsLegacyList.F1, " # ") + 1 as position
from rsLegacyList.F1
where rsLegacyList.F1 LIKE "* # *"

0
投票

使用正则表达式

如果要使用正则表达式,则需要定义一个VBA函数以实例化RegExp对象,将pattern属性设置为类似\s\d\s(whitespace-digit-whitespace)的值,然后调用Execute获得一个或多个匹配项的方法,每个匹配项将提供字符串中模式的索引。如果您想采用这种方法,here是Excel的一些现有示例,但是RegExp操作在MS Access中将是相同的。]

这里是一个示例函数,演示如何使用Execute方法返回的第一个结果:

Public Function RegexInStr(strStr As String, strPat As String) As Integer
    With New RegExp
        .Multiline = False
        .Global = True
        .IgnoreCase = False
        .Pattern = strPat
        With .Execute(strStr)
            If .Count > 0 Then RegexInStr = .Item(0).FirstIndex + 1
        End With
    End With
End Function

注意,以上使用早期绑定,因此您需要在项目中添加对Microsoft VBScript Regular Expressions 5.5

库的引用。

示例即时窗口评估:
?InStr("abc 1 123", " 1 ")
 4 

?RegexInStr("abc 1 123", "\s\w\s")
 4 


使用InStr

在查询中使用内置instr函数的替代方法可能是以下不雅(且可能非常缓慢)的查询:

instr
© www.soinside.com 2019 - 2024. All rights reserved.