首页 > 解决方案 > 正则表达式提取单词

问题描述

我发现目前正则表达式的世界有点大,并且很难继续我的“捕获”。你能帮我上路吗?我正在构建一种搜索引擎,需要组织输入字符串。

给定 VBA 作为工具,而 RegEx 可能是最好的方法,请考虑以下字符串:

input = "header ++add this ++and;a --k101 --k102"

其中“空格”应该在“++”或“--”之前,但用户应该能够搜索“拆分词”

最后我想留下2个数组:
addArr = ["header", "add this", "and;a"]
remArr = ["k101","k102"]

到目前为止,我的思路是先检查“++”,然后检查“--”,然后在我去的时候添加它们

if instr(input,"++")>0 then 
    tmpArr =split(input,"++")
    for i = 1 to ubound(tmpArr) '0 is before the split, 1 is after the split 
       '''Do some regex here'''
    next i
end if

我可能忽略了一种更聪明的方法来实现最终结果,但我可能会补充一点,输入可能会有所不同:(
input = hey ++add this ++and;a没有“--”)
input = hey --remThis ++add this --remAlsoThis
甚至只是 input = hey

所以我必须运行一个测试来检查是否需要正则表达式,如果是我认为我应该运行

Dim RE As Object, ptrn As String
Set RE = CreateObject("vbscript.regexp")
ptrn = "(?)(\+\+)" 'obviously wrong, but "working pattern"
With RE
    .Global = True
    .ignorecase = True
    .Pattern = ptrn
End With
output = RE.Replace(input, "$2")

并以这种方式填充我的数组。但我正在努力找到正确的模式。您能否帮助我制定模式,或引导我走上通往目标的更好道路?

如果它使解决方案有任何不同,我不知道,但我的目标是一个二维数组,其中第二维描述单词/句子是否以“;a”结尾(真或 1 ) 稍后在我的代码中需要...

标签: regexvba

解决方案


正则表达式不是要走的路。通过在结果数组中的每个元素上拆分空格和多个操作来解决它。


推荐阅读