• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ReplaceAll punctuation in a string....

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
s1.replaceAll("[^a-z\\sA-Z]","");
 
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

HTH,
M
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic