2013-05-07 40 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