NullPointerException
NullPointerException

Reputation: 37681

Problems with replaceAll (i want to remove all ocurrences of [*])

i have a text with some words like [1], [2], [3] etc...

For example: houses both permanent[1] collections and temporary[2] exhibitions of contemporary art and photography.[6]

I want to remove these words, so the string must be like this:

For example: houses both permanent collections and temporary exhibitions of contemporary art and photography.

I tryed using: s = s.replaceAll("[.*]", ""); but it just remove the dots (.) from the text.

Wich is the correct way to achieve it?

thanks

Upvotes: 1

Views: 169

Answers (4)

justMe
justMe

Reputation: 2408

Try:

public class StringTest {



    public static void main(String args[]){
        String str = "houses both permanent[1] collections and temporary[2] exhibitions of contemporary art and photography.[6]";
        String patten = str.replaceAll("\\[[0-9]*]", "");

        System.out.println(patten);
    }
}

output:

houses both permanent collections and temporary exhibitions of contemporary art and photography.

Upvotes: 0

OrangeDog
OrangeDog

Reputation: 38777

Step 1: get a better (safer) pattern. Your current one will probably remove most of your string, even if you do get it working as written. Aim for as specific as possible. This one should do (only match brackets that have digits between them).

[\d+]

Step 2: escape special regex characters. [] has a special meaning in regex syntax (character classes) so they need escaping.

\[\d+\]

Step 3: escape for string literal. \ has a special meaning in string literals (escape character) so they also need escaping.

"\\[\\d+\\]"

And now we should have some nicely working code.

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

Upvotes: 2

fge
fge

Reputation: 121750

Use:

s.replaceAll("\\[[^]]+\\]", "")

[ and ] are special in a regular expression and are the delimiters of a character class, you need to escape them. Your original regex was a character class looking either for a dot or a star.

Upvotes: 3

assylias
assylias

Reputation: 328679

It's because [ and ] are regex markers. This should work:

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

(assuming that you always have numbers within the []).

If it could be any characters:

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

(thanks @PeterLawrey).

Upvotes: 9

Related Questions