2015-11-04 26 views
1

我有這兩種字符串匹配和組:正則表達式與可選組部分

<133>[S=88121248] [SID:1073710562] ( lgr_psbrdif)(72811810 ) #38:OpenChannel:on Trunk 0 BChannel:9 CID=38 with VoiceCoder: g711Alaw64k20 VbdCoder: InvalidCoder255 DetectorSide: 0 FaxModemDet NO_FAX_MODEM_DETECTED 

<133>[S=88209541] ( sip_stack)(73281971 ) TcpTransportObject#430::DispatchQueueEvent(EVENT_RECEIVER_DISCONNECT) - Closing connection 

我需要同時匹配並獲得特定的組。我用這個模式:

<(.*)>\[S=(.*)\] (\[SID:(.*?)\])?(.*) 

我速配:

Match0: <133>[S=88121248] [SID:1073710562] ......the full line 
Group1: 133 
Group2: 88121248] [SID:1073710562 
Group3: 
Group4: 
Group5: ......the full line 

Match1: <133>[S=88209541] ......the full line 
Group1: 133 
Group2: 88209541 
Group3: 
Group4: 
Group5: ......the full line 

我需要什麼:

Match0: <133>[S=88121248] [SID:1073710562] ......the full line 
Group1: 133 
Group2: 88121248 
Group3: 1073710562 
Group4: 
Group5: ......the full line 


Match1: <133>[S=88209541] ......the full line 
Group1: 133 
Group2: 88209541 
Group3: 
Group4: 
Group5: ......the full line 

要恢復雙方都很好的比賽,但分組不是。第二個字符串匹配並分組,但第一個沒有。

+0

'<(.*)> \ [S =(*?)\](?:\ [SID:?(*)\])?(。*)'使用此。 –

+0

不要忘記關閉線程(通過接受響應,如果它解決了你的問題)或保持線程活着(通過評論,如果仍有問題)。 – Tomalak

回答

2

您通過使用貪婪的明星.*並因此超出您預期的匹配而犯了一個典型的錯誤。

要在兩個分隔符之間的匹配任何東西,它是更好地使用否定的字符類代替,例如<([^>]*)><>之間。

所以這會工作:

^<([^>]*)>\[S=([^\]]*)\]\s+(?:\[SID:([^\]]*)\]\s+)?(.*) 

擊穿:

^<([^>]*)>    # something between <and> at the start of the line 
\[S=([^\]]*)\]\s+   # something between "[S=" and "]" 
(?:\[SID:([^\]]*)\]\s+)? # something between "[SID:" and "]", optional 
(.*)      # rest of the string 

注意非捕獲括號(?:...),它們會在結果排除未使用的組。

相配:

MATCH 1 
1. [1-4] `133` 
2. [8-16] `88121248` 
3. [23-33] `1073710562` 
4. [35-218] `( lgr_psbrdif)(72811810 ) #38:OpenChannel:on Trunk 0 BChannel:9 CID=38 with VoiceCoder: g711Alaw64k20 VbdCoder: InvalidCoder255 DetectorSide: 0 FaxModemDet NO_FAX_MODEM_DETECTED ` 

MATCH 2 
1. [220-223] `133` 
2. [227-235] `88209541` 
3. n/a 
4. [237-360] `( sip_stack)(73281971 ) TcpTransportObject#430::DispatchQueueEvent(EVENT_RECEIVER_DISCONNECT) - Closing connection ` 
+0

它的工作,感謝您的時間。 –