Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ReplaceAll punctuation in a string....

 
Chris Parkinson
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I've got a problem with a string
For example if I have a string s1 = "There w@s a b1g monster!!";
I want to remove everything, and end up with the following string:
s2 = "There ws a bg monster"
So I want to remove all the punctuation and numbers
I think I could do the following, but I dont want to repeat this for every punctuation character that I want removed from the string.
s2 = s1.replaceAll("!", "");
Is there an easy way?? ... thanks for your time!
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at java.lang.regex - presuming you are using a JDK after 1.4. Your sort of problem is what this package was designed for.
 
Chris Parkinson
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah thanks, java.util.regex looks very useful, but I'm finding it difficult to understand.
If I use the regular expression syntax \w it matches a word character: [a-zA-Z_0-9]
How do I search my string for these word characters only using regex, and then put this in a new string?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might find it a bit easier to iterate through the characters in the String (with a for-loop), and make use of a method or two in the Character class. As different characters pass the test, you could just append them to a new String (or StringBuffer).
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s1.replaceAll("[^a-z\\sA-Z]","");
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

HTH,
M
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic