/*
******* java实现UBB代码 *************
*****************************************
* 源文件名: UbbCode.java
*
* 作者:梦想年华
* Email:fanwsp@126.com
* HomePage:http://wsp.hniuca.net
* QQ:122142023
* CopyRight(c)2005-2006 by DreamTime
*
*/
package dreamtime.guestbook; //指定类所在的包
import java.util.regex.Matcher; //导入所需要的类
import java.util.regex.Pattern;
public class UbbCode //类定义
{
private String source; //待转化的HTML代码字符串
private String ubbTags[]; //UBB标记数组
private String htmlTags[]; //HTML标记数组
//初始化,分别为UBB标记数组和HTML标记数组赋值
public UbbCode()
{
byte byte0 = 74;
source = new String();
ubbTags = new String[byte0];
htmlTags = new String[byte0];
ubbTags[0] = "[b]";
htmlTags[0] = "";
ubbTags[1] = "[/b]";
htmlTags[1] = "";
ubbTags[2] = "[i]";
htmlTags[2] = "";
ubbTags[3] = "[/i]";
htmlTags[3] = "";
ubbTags[4] = "[quote]";
htmlTags[4] = "
private String replace(String s, String s1, String s2)
{
StringBuffer stringbuffer = new StringBuffer();
for(int i = 0; i < s1.length(); i++)
{
char c = s1.charAt(i);
switch(c)
{
case 91: // '['
stringbuffer.append("\\[");
break;
case 93: // ']'
stringbuffer.append("\\]");
break;
default:
stringbuffer.append(c);
break;
}
}
Pattern pattern = Pattern.compile(stringbuffer.toString());
Matcher matcher = pattern.matcher(s);
StringBuffer stringbuffer1 = new StringBuffer();
for(boolean flag = matcher.find(); flag; flag = matcher.find())
matcher.appendReplacement(stringbuffer1, s2);
return matcher.appendTail(stringbuffer1).toString();
}
private String replaceNormalUBBCode(String s)
{
String s1 = new String(s);
for(int i = 0; i < ubbTags.length; i++)
s1 = replace(s1, ubbTags[i], htmlTags[i]);
return s1;
}
private String replaceURL(String s)
{
StringBuffer stringbuffer = new StringBuffer(s);
String s1 = new String();
int i = s.indexOf("[url]");
int j = s.indexOf("[/url]");
if(i != -1 && j != -1 && i < j)
{
String s2 = s.substring(i + 5, j);
String s3 = "" + s2 + "";
stringbuffer.replace(i, j + 6, s3);
}
return stringbuffer.toString();
}
private String replaceEmail(String s)
{
StringBuffer stringbuffer = new StringBuffer(s);
String s1 = new String();
int i = s.indexOf("[email]");
int j = s.indexOf("[/email]");
if(i != -1 && j != -1 && i < j)
{
String s2 = s.substring(i + 7, j);
String s3 = "" + s2 + "";
stringbuffer.replace(i, j + 8, s3);
}
return stringbuffer.toString();
}
public void setSource(String s)
{
source = s;
}
public String getResult()
{
return source;
}
public void run()
{
for(source = replaceNormalUBBCode(source);
source.indexOf("[url]") != -1 && source.indexOf("[/url]") != -1;
source = replaceURL(source));
for(; source.indexOf("[email]") != -1 && source.indexOf("[/email]") != -1; source = replaceEmail(source));
}
}