2013-05-07 38 views
-1

我在regex中很弱,我認爲我已經分配的任務需要regex。 假設我有以下字符串#B#Objectives:#B#We aimed to review how personality characteristics contribute to the onset, maintenance or modulation of.#B#Method:#B#The databases Medline and PsychINFO were examined from 1967 to 2012 to用html div取代某些模式

現在我的要求是用<div class="format">anystring</div>替換#B#anystring#B#

我認爲regex是必需的,但我不知道什麼是正則表達式。

請給出任何建議。

更新

String regex="#B#"; 
String textFormated = text.replaceAll(regex,"<div class='formated'>"); 
System.out.println(textFormated); 

這就是我想直到now.It剛剛替換#B#<div class='formated'>但如果:#B#被發現有輕微的併發症,增加股利div.The結束的結束應該加入但這兩個正則表達式如何一起使用。

+0

你有什麼已經做了?你試過的任何代碼? – Howard 2013-05-07 05:30:07

回答

2

使用此:

str = str.replaceAll("#B#(.*?)#B#", "<div class=\"format\">$1</div>"); 

.*?不願意預選賽。這意味着,它匹配儘可能少的字符(可能爲零),直到下一個#B#

+0

thnks,但你能告訴我使用$ 1和$ 2時@Rakesh Chouhan使用的最大差異 – ntstha 2013-05-07 14:46:00

+0

這個數字是括號中的表達數。 $ 0是整個比賽,$ 1是第一個括號匹配等。$ 1在我的情況是正確的,$ @在@Rakesh Chouhan的情況下是正確的。他的解決方案也是正確的,但如果#B#之間沒有文字,#B#將會輸出。 – Oliv 2013-05-09 08:25:04

1

試試這個代碼,這將幫助你

String givenData ="asdfasdfa#B#anystring#B#asdfasdfasdfas"; 
String pattern = "(#B#)(.+?)(#B#)"; 
String result = givenData.replaceAll(pattern, "<div class='format'>$2</div>"); 
System.out.println(result); 
+1

'#B#'的捕獲組是冗餘的...... – nhahtdh 2013-05-07 05:53:03