2014-01-08 43 views
0

我使用VB.net和PStools創建一個簡單的程序工作,所以我們可以看到一個人是否登錄到多臺PC。正則表達式與vb.net和PStools

,當我運行代碼:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 

    Dim Proc As New System.Diagnostics.Process 
    Proc.StartInfo = New ProcessStartInfo("psloggedon") 
    Proc.StartInfo.RedirectStandardOutput = True 
    Proc.StartInfo.UseShellExecute = False 
    Proc.StartInfo.CreateNoWindow = True 
    Proc.Start() 

    TextBox2.Text = Proc.StandardOutput.ReadToEnd 

    Proc.Close() 
End Sub 

我得到的結果:

"Users logged on locally: 
    1/1/2014 4:14:43 PM  Joseph_Garza\Joseph.Garza 

No one is logged on via resource shares." 

然而,它說: 「Joseph_Garza」 它會說我的公司名稱。

所以.. COMPANY_NAME \ Joseph.Garza

我如何使用正則表達式來獲得:

1.the time and date 
2.Joseph.Garza 

回答

0

也許你可以使用正則表達式?

Users logged on locally:\s*((?:(?!\s{2,}).)*)\s*([^\\]*)\\(\S+) 

regex101 demo

Users logged on locally:比賽字面上。

\s*匹配0個或多個空格,製表符和換行符。

((?:(?!\s{2,}).)*)這裏最外面的parens用於存儲捕獲。內部部分是一種模式,用於匹配除連續兩個或更多空格之外的每個字符。 (?!\s{2,})是阻止超過2個空格的匹配並且正在使用負向預覽(?! ...){2,}表示\s正在重複至少兩次。 .是一個通配符,它​​匹配除換行符之外的所有字符。

([^\\]*)最外面的parens用於存儲第二部分。內部部分是匹配每個字符的圖案,除了反斜槓\[^ ... ]是一個否定類,它會匹配裏面的所有內容而不是

\\匹配單個反斜槓和...

(\S+)用來匹配非空格,非換行,非製表符,並存儲了比賽。

而且在VB中實現它:

Imports System.Text.RegularExpressions 

Module Example 
    Public Sub Main() 
     Dim pattern As String = "Users logged on locally:\s*((?:(?!\s{2,}).)*)\s*([^\\]*)\\(\S+)" 
     Dim input As String = "Users logged on locally:" & vbCrlf & _ 
          "  1/1/2014 4:14:43 PM  Joseph_Garza\Joseph.Garza" & vbCrlf & _ 
          "No one is logged on via resource shares." 
     Dim match As Match = Regex.Match(input, pattern) 
     If match.Success Then 
     For ctr As Integer = 1 To match.Groups.Count - 1 
      Dim captureCtr As Integer = 0 
      For Each capture As Capture In match.Groups(ctr).Captures 
       Console.WriteLine("Matches: {1}", _ 
           captureCtr, capture.Value) 
       captureCtr += 1     
      Next 
     Next 
     End If  
    End Sub 
End Module 

ideone demo

注:我剛加入公司名稱,以防萬一,但如果你絕對不需要,只需要使用這個regex

Users logged on locally:\s*((?:(?!\s{2,}).)*)\s*[^\\]*\\(\S+) 

(的周圍[^\\]*除去括號)