我目前正在測試的正則表達式模式匹配如下:bbcode中的十六進制顏色代碼的正則表達式?
[#123456]
[#aabc36]
然後轉換爲HTML代碼:
<FONT COLOR="#123456">
但是,如果模式,如:
[/#123456]
然後將其替換爲
</FONT>
我曾嘗試以下方式:
\\[#[A-Fa-f0-9]{6}\\]|\\[[A-Fa-f0-9]{3}\\]
,但它失敗。
而我想要的是將提取的顏色十六進制代碼轉換爲HTML字體顏色以進行替換。下面
的是我的正則表達式替換方法:
public String replaceColor(String text , String imageLocation){
StringBuffer imageBuffer = new StringBuffer ("");
String bbcode = "\\[#[A-Fa-f0-9]{6}\\]|\\[[A-Fa-f0-9]{3}\\]";
Pattern pattern = Pattern.compile(Pattern.quote(bbcode));
Matcher matcher = pattern.matcher(text);
//populate the replacements map ...
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
//String orginal = replacements.get(matcher.group(1));
imageBuffer.append("<FONT COLOR=\"#123456\">");
String replacement = imageBuffer.toString();
builder.append(text.substring(i, matcher.start()));
if (replacement == null) {
builder.append(matcher.group(0));
} else {
builder.append(replacement);
}
i = matcher.end();
}
builder.append(text.substring(i, text.length()));
return builder.toString();
}
刪除'Pattern.quote',這是逃避所有的正則表達式元字符在'bbcode'。 –
如何提取[]之間的bbcode單詞? –