Reputation: 33
I have a String of text that contains various urls surrounded by [url]
For example:
And I want it to read like this:
I've tried:
String test = body3.replaceAll("[url]", "");
But I end up still with the brackets []
Upvotes: 0
Views: 3459
Reputation: 850
In a regular expression, square brackets are used to specify a range of items to match, so [url] will match the characters, u, r and l.
To match an actual square bracket, you will need to escape it by prefixing it a backslash
\[
But a single backslash will also need to be escaped in java, so you need to precede the square brackets with two backslashes.
So to remove the url block with replaceAll, you could use
String text = "[url]http://www.example.com[/url]";
String replaced = text.replaceAll("\\[[url/]+\\]", "");
System.out.println("replaced = " + replaced);
Upvotes: 0
Reputation: 164
Try this. It seems you want both [url],[/url] to be replaced with empty spaces.
String a = "Example text [url]http://www.example.com[/url] Example text";
String[] b = {"[url]","[/url]"};
String[] c = {"",""};
StringUtils.replaceEach(a,b,c);
result will be : Example text http://www.example.com Example text.
Remember that if you want to replace number of strings with corresponding empty strings or any other string you can do it in above way.
Upvotes: 0
Reputation: 521249
You could try using a regex replacement:
String input = "Example text [url]http://www.example.com[/url] Example text";
input = input.replaceAll("\\[url\\](.*?)\\[/url\\]", "$1");
Demo here:
Upvotes: 1