2014-12-04 93 views
0

對於這個代碼,我有在使用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

而不是捕捉全線,捕獲所需的數據

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 
+0

試過,它的工作。謝謝! – ladiesman1792 2014-12-04 07:01:52

+0

「actions.Add」K「'有什麼用? – ladiesman1792 2014-12-04 07:20:41

+0

@ ladiesman1792,在將數據添加到'scripting.dictionary'時,必須在每個包含的元素中包含一個*唯一鍵*。對於發佈的代碼,我有習慣將*「K」*前綴作爲視覺線索來標識添加*鍵*的位置。但它不是必需的。 – 2014-12-04 07:45:45