سؤال

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

[#123456]

[#aabc36]

I have tried #[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3} and successfully match #aabc36 but when it comes to adding the brackets [] , it fails.

I have tried below pattern for matching

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

The below is my method for regex replacement

 public String replaceColor(String text , String bbcode , String imageLocation ){

    //"\\[("+bbcode+")\\]" for [369] , [sosad] 

    // String imageLocation = "file:///android_asset/smileyguy.png";
    // builder.append("<img src=\"" + imageLocation + "\" />");

    StringBuffer imageBuffer = new StringBuffer (""); 
    // Pattern pattern = Pattern.compile("\\"+bbcode);
    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("<img src=\"" + imageLocation + "\" />");
        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();
}
هل كانت مفيدة؟

المحلول

To match [ , ] literally, you should escape them. Otherwise it is used as metacharacter that represents a set of characters.

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

In Java string litearls, \ should be escaped.

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

نصائح أخرى

You need to escape the brackets with a \ in order to match on them as they are a regex symbol:

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

In a Java string you will also need to escape the backslash so:

 String pattern = "\\[#[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}\\]";

If you want to include brackets in the pattern to match you must escape them with a . But because java already uses \ as an escape character you must use two of them "\[...\]"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top