2016-05-15 68 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