2016-05-15 83 views
1

我有一些正則表達式來在標籤之間放置內容,如結果所示。如果我申請上導致文字相同的正則表達式表達我會得到標籤內的標籤......匹配特定不在標籤之間

原創內容:

Lorem存有悲123456坐在@twitter阿梅德, consectetur adipiscing ELIT例子。

結果:

Lorem存有[聯繫電話] 123456 [/電話]悲仰臥[總重量] @twitter [/ TW] 阿梅特,consectetur adipiscing ELIT並[a]例如,[/ A]。

RESULT第二時間:

Lorem存有[電話] [電話] 123456 [/電話] [/電話]悲坐 [總重量] [總重量] @twitter [/ TW] [/ tw] amet,consectetur adipiscing elit [a] [a] example [/ a] [/ a]。

什麼把我的正則表達式,以便不匹配,如果內容介於任何[]和[/]之間?

+0

嘗試增加'(?!\ [\/[^] *])'到你的正則表達式模式的結束。 –

+0

下面的答案是解決方法,而不是解決方案。 –

回答

0

說明

(?:[0-9]+|twitter|consectetur)(?![0-9a-z]*\[\/[a-z]+\]) 

替換爲:[xx]$0[/XX]

Regular expression visualization

這個正則表達式將執行以下操作:

  • 找到號碼的所有字符串,字twitter,和單詞consectetur。我選擇了這些子字符串來說明正則表達式,但是這些可以用其他字符串替換。
  • 驗證字尚未後跟一個結束標記
  • 避免邊緣例
    • 構建[0-9+]將匹配2345,其是源串中,但是它可能已經由標籤
    • 匹配被包裹twitter沒有前導@仍具有尾隨標籤

實施例

現場演示

https://regex101.com/r/lW2pY6/1

示例文本

123456 Lorem存有[聯繫電話] 123456 [/電話]悲仰臥[總重量] @twitter [/ TW ] amet,consectetur adipiscing elit [a] example [/ a]

樣品代換後

[XX] 123456 [/ XX] Lorem存有[聯繫電話] 123456 [/電話]悲仰臥[總重量] @twitter [/ TW]阿梅特,[XX] consectetur [/ XX ] adipiscing ELIT [A]例如[/ A]

說明

NODE      EXPLANATION 
---------------------------------------------------------------------- 
    (?:      group, but do not capture: 
---------------------------------------------------------------------- 
    [0-9]+     any character of: '0' to '9' (1 or more 
          times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    twitter     'twitter' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    consectetur    'consectetur' 
---------------------------------------------------------------------- 
)      end of grouping 
---------------------------------------------------------------------- 
    (?!      look ahead to see if there is not: 
---------------------------------------------------------------------- 
    [0-9a-z]*    any character of: '0' to '9', 'a' to 'z' 
          (0 or more times (matching the most 
          amount possible)) 
---------------------------------------------------------------------- 
    \[      '[' 
---------------------------------------------------------------------- 
    \/      '/' 
---------------------------------------------------------------------- 
    [a-z]+     any character of: 'a' to 'z' (1 or more 
          times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    \]      ']' 
---------------------------------------------------------------------- 
)      end of look-ahead 
相關問題