Lena Bru
Lena Bru

Reputation: 13947

how to replace all instances of "[" and "]"

I have a string that looks like this: [hello world] and i want to get hello world

having hard time finding the right regex for the replaceAll method for java

String s = s.replaceAll("[[]]",""); throws an exeption

what is the right regex for it ?

Upvotes: 1

Views: 96

Answers (4)

upog
upog

Reputation: 5531

try this

public class Test {

    public static void main(String args[]){
        String s =  "[hello world]";
        s= s.replaceAll("\\[", "").replaceAll("\\]", "");
        System.out.println(s);
    }

}

Upvotes: 1

Reimeus
Reimeus

Reputation: 159844

[ and and ] are meta-characters used to define the bounds of a character class. They need to be escaped to be used within a regular expression themselves

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

Upvotes: 5

Rahul Tripathi
Rahul Tripathi

Reputation: 172528

You can try this:-

String s = string.replace("[", "").replace("]", "");

Upvotes: 2

Josh M
Josh M

Reputation: 11947

Perhaps you should try using replace instead:

String s = string.replace("[", "").replace("]", "");

Or it seems like you could just get away with using substring:

String s = string.substring(1, string.length()-1);

Upvotes: 4

Related Questions