如何从字符串中选择和裁剪某些字符?

时间:2014-12-04 06:23:51

标签: regex string search text vbscript

对于此代码,我在使用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

1 个答案:

答案 0 :(得分: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