aspose file tools*
The moose likes Beginning Java and the fly likes ReplaceAll punctuation in a string.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ReplaceAll punctuation in a string...." Watch "ReplaceAll punctuation in a string...." New topic
Author

ReplaceAll punctuation in a string....

Chris Parkinson
Greenhorn

Joined: Mar 14, 2004
Posts: 8
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

Joined: Mar 16, 2004
Posts: 140
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

Joined: Mar 14, 2004
Posts: 8
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

Joined: Dec 10, 2001
Posts: 7023
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).


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
s1.replaceAll("[^a-z\\sA-Z]","");
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118

HTH,
M


Java Regular Expressions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ReplaceAll punctuation in a string....
 
Similar Threads
Code compiles fine but stuck in the runtime
Recursive anagram problem
remove space inbetween words
String String String
palindrome program