2017-05-26 1025 views
2

這個問題可能很簡單,但我是RegEx和此論壇的新手,並且無法在任何地方找到答案。如何使用正則表達式來匹配不連續的字符串

我的電子郵件進入Microsoft Outlook中通常是這樣的:


病人:SMITH,JANE

MRN:12345678

EncounterID:1234567890

EncounterDate :Apr 11 2017 12:00 12:00

部:神經病學

中心:頭痛

地點:校本部

訪問類型:全新NEUR頭痛

主治物理學:JONES,MARY


我希望Outlook能夠在每封電子郵件到達時檢查它,sele ct那些主題行表明他們有相關信息的人,然後提取MRN,病人的姓氏,病人的名字和遇到的日期。

當有新郵件到達時,我的模塊運行以下子:

Public Sub ProcessImatchKpEmails(item As Outlook.MailItem) 
Dim LastName As String 
Dim FirstName As String 
Dim EncounterDate As String 
Dim MRN As String 
Dim Body As String 

On Error Resume Next 

' Check to make sure it is an Outlook mail message. 
    If TypeName(item) <> "MailItem" Then Exit Sub 
    Body = item.Body 

' Exract data from the email 
    If item.Subject = _ 
     gImatchKpEmailSubjectNo Or item.Subject = _ 
     gImatchKpEmailSubjectYes Or _ 
     item.Subject=_gImatchKpEmailSubjectMaybe Then 
      MRN = ExtractText(Body, RegPattern("MRN")) 
      LastName = ExtractText(Body, RegPattern("LastName")) 
      FirstName = ExtractText(Body, RegPattern("FirstName")) 
      EncounterDate = ExtractText(Body, RegPattern("EncounterDate")) 
    End If 
End Sub 

RegPattern功能如下:

Public Function RegPattern(Lookup As String) As String 'Creates a 
    regPattern for each type of lookup 

On Error Resume Next 

    Select Case Lookup 
     Case "LastName" 
      RegPattern = "Patient\s*[:]+\s*(\w*)\s*" 
     Case "FirstName" 
      RegPattern = "Patient\s*[:]+\s*(\w*)[,](\w*)\s*" 
     Case "EncounterDate" 
      RegPattern = "EncounterDate\s*[:]+\s*(\w*)\s*" 
     Case "MRN" 
      RegPattern = "MRN\s*[:]+\s*(\d*)\s*" 
    End Select 

    Debug.Print Lookup, RegPattern 

End Function 

ExtractText功能如下:

Public Function ExtractText(Str As String, RegPattern As String) As 
    String 
Dim regEx As New RegExp 
Dim numMatches As MatchCollection 
Dim M As Match 

On Error Resume Next 

regEx.Pattern = RegPattern 

Set numMatches = regEx.Execute(Str) 
If numMatches.Count = 0 Then 
    ExtractText = "missing" 
Else 
    Set M = numMatches(0) 
    ExtractText = M.SubMatches(0) 
End If 

Debug.Print ExtractText 
End Function 

當我運行這個,代碼拿起新的電子郵件,它管理s準確地拉出MRN(12345678)和患者姓名(Smith)。

但是,它也將(患者名字)拉爲(史密斯)。同樣,它會將遇到的日期拉爲(Apr),但是會丟失其餘的。

有人可以告訴我什麼合適的RegEx代碼將獲得患者的名字,以及整個相遇日期?

感謝您的幫助。

+1

Outlook可以運行vbscript代碼嗎? – sln

+0

但是,這個'Patient \ s * [:] + \ * *(\ w *)\ s *'一次檢查一個正則表達式只會匹配一組單詞。我認爲這是最後一個名字。另外,vbsctipt(或vba?)是否遵循雙引號規則(即轉義必須轉義)? – sln

+0

好吧,看起來你應該使用1個正則表達式來獲得最後一個名字。使用'First'名稱,在組1中獲得_last_,在組2中獲得_first_。建議:如果它沒有名字,不要求在正則表達式中使用。 '病人\ s * [:] +(?:\ s *(\ w +)(?:\ s *,\ s *(\ w +))?)?' – sln

回答

-1
"Patient\s*[:]+\s*(\w*)[,](\w*)\s*" 

的核心問題是,你隨時提取0號子匹配;但是你有兩組捕捉括號。改變第一組括號到非捕捉,那些應該幫助:

"Patient\s*[:]+\s*(?:\w*)[,](\w*)\s*" 

,甚至無需名字:沒有括號,因爲沒有理由你應該需要分組那裏。

還要注意的是[:]是相同的:,你可能想捕捉的名字至少一個字符,這是\w+,而不是\w*

+0

謝謝你的幫助。 – schniggeldorf