简体   繁体   English

Java Regex模式与括号不匹配

[英]Java Regex pattern not matching brackets

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. 我尝试了#[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}并成功匹配#aabc36但是在添加方括号[]时,它失败了。

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. 在Java字符串litearls中, \\应该转义。

"\\[#[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: 在Java字符串中,您还需要转义反斜杠,因此:

 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 "\\[...\\]" 但是因为Java已经使用\\作为转义字符,所以必须使用其中两个“ \\ [... \\]”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM