2015-06-26 19 views
1

在Java中,使用正則表達式僅在配對哈希標籤中刪除內容有更快的方法嗎? 我會舉一些例子:使用Java RegEx刪除配對主題標籤之間的內容##

When user logs in ## //Expected Result: When user logs in ## 
When user logs in # //Expected Result: When user logs in # 
When user logs in #the system# //Expected Result: When user logs in ## 
When user logs in #the system //Expected Result: When user logs in #the system 
When user logs in #the system# named #test //Expected Result: When user logs in ## named #test 

我見過的例子刪除括號中的內容,但,這是因爲一點點不同「(」和「)」是不同的字符,如果我只是使用replace,編譯器不能到#the system##test

回答

1
之間

區分內容您可以使用:

str = str.replaceAll("(?!<#)#[^#]+#(?!#)", "##); 

RegEx Demo

+0

#。*?# 將是另一種選擇! – Keews

+0

我在我的解決方案中使用了'#。+?#',而不是'#。*?#',因爲OP希望保持###不變。 – anubhava

+0

你是完全正確的,我的錯!抱歉。 – Keews

相關問題