我目前正在尝试测试与以下内容匹配的正则表达式模式:
[#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();
}
最佳答案
试试这个
s = s.replaceAll("\\[#(\\w{6}|\\w{3})]", "<FONT COLOR=\"#$1>\">")
.replaceAll("\\[/#(\\w{6}|\\w{3})]", "</FONT>");
关于java - bbcode 中十六进制颜色代码的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20985381/