Reputation: 37681
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
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
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
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
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