2016-07-14 81 views
1

我有一個數量的字符串,其中第一個是如何在首次出現幾個字符串之一時提取目標字符串的最後一部分?

"The quick brown fox jumped over the lazy dog". 

我有一個關鍵字列表(在這種情況下,相關的有「褐色」和「懶惰」)。我正在嘗試構造一個將通過目標字符串爬行的正則表達式,並且在關鍵字的第一個實例中,將返回字符串的其餘部分。我創建了下面的正則表達式:

.*?(?=(brown|lazy)) 

這提取第一次出現,但由於某些原因,我無法弄清楚如何獲得字符串的其餘部分(即「棕色狐狸跳過了懶狗」),而不從第二次出現開始。非常感謝這方面的建議。非常感謝

這是使用正則表達式5.5庫在VBA做

Function regexmatch(Myrange As Range) As String 
Dim regEx As New RegExp 
Dim strPattern As String 
Dim strInput As String 
Dim strReplace As String 
Dim strOutput As String 

strPattern = ".*?(?=(brown|lazy))" 

If strPattern <> "" Then 
    strInput = Myrange.Value 
    strReplace = "" 

    With regEx 
     .Global = True 
     .MultiLine = True 
     .IgnoreCase = True 
     .pattern = strPattern 
    End With 

    If regEx.test(strInput) Then 
     regexmatch = regEx.replace(strInput, strReplace) 
    Else 
     regexmatch = "" 
    End If 
End If 
End Function 
+2

爲什麼這麼複雜? '(brown | lazy)*'(或'(?:brown | lazy).''應該足夠了。或者如果你在比賽中不需要「褐色」或「懶惰」,那麼捕獲「(。*)」並獲取它的值。什麼是工具/正則表達式?請分享您的代碼。 –

+1

選中此:https://regex101.com/r/iM9fL0/1 –

+0

Hi @WiktorStribiżew。我很抱歉,我應該在帖子中提供更多細節,因爲我突然意識到它完全改變了你的答案!很多道歉! – Chaz

回答

0

有兩件事情可以做,但實際上,我只是建議:

strPattern = "^.*?(brown|lazy)" 
... 
strReplace = "$1" 
... 
With regEx 
    .Global = False 

,然後你會得到:

enter image description here

注:

  • 你只需要1更換被執行,因此,替換操作應該是單一的,.Global必須False
  • ^使得在字符串開始掛靠模式,它只能作用於的開始處匹配字符串
  • 向前看是多餘的,您可以使用捕獲組(brown|lazy)並用取回的值反向引用$1替換整個匹配。
相關問題