简体   繁体   中英

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

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).

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.

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+\\]", "");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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