【问题标题】:How can I select and crop certain characters from a string?如何从字符串中选择和裁剪某些字符?
【发布时间】:2014-12-04 06:23:50
【问题描述】:

对于这段代码,我在使用 MID 和 INSTR 函数时遇到了问题:

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set file = objFSO.OpenTextFile("sample.txt" , ForReading)  
Const ForReading = 1

Dim re
Dim controller
Dim action
Set re = new regexp 
re.pattern = "(contextPath\s*?[+]\s*?[""][/]\w+?[?]action[=]\w+?[""])"
re.IgnoreCase = True
re.Global = True

Dim line
Do Until file.AtEndOfStream
    line = file.ReadLine
    For Each m In re.Execute(line)

        var = m.Submatches(0)

        'I am having a problem with the next two lines:

        controller = Mid(var, 1, InStr(var, "contextPath\")) & "[?]action[=]\w+?[""]n"
        action = Mid(var, 1, InStr(var, "contextPath\s*?[+]\s*?[""][/]\w+?[?]action[=]")) & """"

        Wscript.Echo "controller :" & controller
        Wscript.Echo "action: " & action
    Next
Loop

带有文本文件“sample.txt”:

contextPath+"/GIACOrderOfPaymentController?action=showORDetails"
contextPath +"/GIACPremDepositController?action=showPremDep"
contextPath+ "/GIACCommPaytsController?action=showCommPayts"

(注意加号(+)旁边的空格)

我怎样才能使输出看起来像这样:

controller: GIACOrderOfPaymentController
controller: GIACPremDepositController
controller: GIACCommPaytsController

action: showORDetails
action: showPremDep
action: showCommPayts

【问题讨论】:

    标签: regex string search text vbscript


    【解决方案1】:

    不是捕获整行,而是捕获所需的数据

    Option Explicit
    
    Const ForReading = 1
    
    Dim re
        Set re = New RegExp
        With re 
            .Pattern = "contextPath\s*\+\s*\""/(\w+)\?action=(\w+)\"""
            .IgnoreCase = True 
            .Global = True 
        End With
    
    Dim controllers, actions
        Set controllers = CreateObject("Scripting.Dictionary")
        Set actions = CreateObject("Scripting.Dictionary")
    
    Dim file
        Set file = CreateObject("Scripting.FileSystemObject").OpenTextFile("sample.txt" , ForReading)  
    
    Dim line, m
        Do Until file.AtEndOfStream
            line = file.ReadLine
            For Each m In re.Execute(line)
                controllers.Add "K" & controllers.Count, m.Submatches(0)
                actions.Add "K" & actions.Count, m.Submatches(1)
            Next
        Loop
    
    Dim item
    
        For Each item in controllers.Items()
            WScript.Echo "controller: " & item
        Next 
    
        WScript.Echo ""
    
        For Each item in actions.Items()
            WScript.Echo "action: " & item
        Next 
    

    【讨论】:

    • actions.Add "K"有什么用?
    • @ladiesman1792,在向scripting.dictionary 添加数据时,需要为包含的每个元素添加一个唯一键。对于已发布的代码,我习惯于包含 "K" 前缀作为视觉线索,以识别添加 key 的位置。但这不是必需的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多