java.util.regex.PatternSyntaxException: Unclosed character class near index 0

前端 未结 1 1573
难免孤独
难免孤独 2020-12-11 16:10

I am trying to replace all square brackets i my string .

This is my program

   package com;

import java.util.ArrayList;

import org.apache.commons.         


        
相关标签:
1条回答
  • 2020-12-11 16:39

    String.replaceAll takes a regular expression pattern, but you don't need regular expressions at all. You can use:

    str = str.replace("[", "").replace("]", "");
    

    Or you could use a regex if you wanted, replacing both in one go:

    str = str.replaceAll("[\\[\\]]", "");
    

    That's saying "replace any character in the set (open square bracket, close square bracket) with the empty string. The \\ is to escape the square brackets within the set.

    Note that you need to use the result of replace (or replaceAll) - strings are immutable in Java, so any methods like replace don't modify the existing string, they return a reference to a new string with the relevant modifications.

    0 讨论(0)
提交回复
热议问题