Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

To replace square brackets from a string

 
Abhinand Kunjayyappan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Please let me know how to replace [ and ] from a string.

code :
public class Test{
public static void main(String[] args) {
String s = "a\n\"a\"\ta\n [q]\\q$\tq";
System.out.println(s);
s = s.replaceAll("[\\n\\t\\\\\"$/]*"," ");
System.out.println(s);
}
}

In this code i want to replace [ and ] from string s with space.
What should i add to the regular expression to do this.

Thanks Abhinand
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an Advanced question at all. Please CarefullyChooseOneForum.

If you want to include square brackets within a list of characters [abc...] in a regular expression, I think you escape them with backslashes. Unfortunately, you then have to escape the backslashes.
 
Abhinand Kunjayyappan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i changed my codeto replace [ and ].Now it is working

code:

public class Test{
public static void main(String[] args) {
String s = "a\n\"a\"\ta\n [q]\\q$\tq";
System.out.println(s);
s = s.replaceAll("[\\n\\t\\\\\"$/]*"," ").replace('[',' ').replace(']',' ');
System.out.println(s);
}
}

Thanks
Abhinand
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic