Roshanck
Roshanck

Reputation: 2290

How to remove a special character pattern in a string

I have a string name s,

String s = "He can speak English and Sinhala.[1]He<ename> has edited 12 CSE Staff Research Publications.[1][2]"

I want to remove [1] and [1][2] from the string. Note that we can have any number within the square brackets and any no of square brackets(like [number][number][number]...). I tried using this,

String removedNoTag = s.replaceAll("[\\[0-9\\]]","");

Yes it removes all [number].. patterns. But it also removes all numbers within the text(It removes 12 also).

Can anyone please tell me how to do this?

Upvotes: 1

Views: 473

Answers (4)

Brian Agnew
Brian Agnew

Reputation: 272237

Your outer brackets define a set of characters to remove. That set is defined as [,] and 0-9. So any combination of those is detected (for example [], 2, ], [3], [324], ]1[[[).

Instead try \\[\\d+\\], which means the open bracket, one or more digits (\d) and a closing bracket.

Upvotes: 2

kgautron
kgautron

Reputation: 8263

Because it removes any instance of a character that is either a number or a bracket.

replace with : \\[[0-9]+\\]

Upvotes: 1

RoToRa
RoToRa

Reputation: 38390

You are escaping the wrong brackets in your regular expression. What you are looking for is:

String removedNoTag = s.replaceAll("\\[[0-9]+\\]","");

or

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

With \d being the "short form of [0-9].

Upvotes: 3

godspeedlee
godspeedlee

Reputation: 672

try with this: String removedNoTag = s.replaceAll("\\[\\d+\\]","");

Upvotes: 3

Related Questions