I am currently trying to test the regex pattern matching the following:

[#123456]

[#aabc36]

And then convert to HTML codes:

<FONT COLOR="#123456">

But if pattern like:

[/#123456]

then to be replaced as

</FONT>

I have tried the following pattern:

\\[#[A-Fa-f0-9]{6}\\]|\\[[A-Fa-f0-9]{3}\\]

but it fails.

And what I want to is to get the extracted color hex code to the HTML font color for replacement.

The below is my method for regex replacement:

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();
}
有帮助吗?

解决方案

try this

    s = s.replaceAll("\\[#(\\w{6}|\\w{3})]", "<FONT COLOR=\"#$1>\">")
             .replaceAll("\\[/#(\\w{6}|\\w{3})]", "</FONT>");

其他提示

You need to remove the Pattern.quote call, which is making your regex match all literal characters. If you want to capture part of the match, you need use a match group (). To simplify it, change your expression to this:

String bbcode = "\\[(#[A-Fa-f0-9]{3}([A-Fa-f0-9]{3})?)\\]";

And use matcher.group(1) to reference the part between the square brackets.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top