Skip to main content

Posts

Showing posts from April 19, 2012

How to remove non-alphabets from a String

This post is all about how to remove all characters that are not alphabets from a String. For the reverse of the same, refer here. For eg, if you want to only "ABC" from "A1@348474B*&C" then the following snippet of code would be fine in Java.

String test = "A1@348474B*&C";
test = test.replaceAll("[a-zA-Z]",""); //This will replace all non alpha characters
System.out.println("The extracted String is "+test);

The output of the above code will be,

The extracted String is ABC

Hope this was helpful to you in someway. Happy Working...

How to extract numbers from a String

This is a simple post on how to extract numbers from a String. I had tried too many methods for the same, and though performance wise this solution cannot be the same, it certainly is the most simple solution that I ever come across. I got this solution  from CodeRanch or StackOverflow (not sure), but thought better to blog so that I can refer it easily later. ..:)

String test = "ABC10DEF20";
test = test.replaceAll("\\D",""); //This will replace all non numeric characters with 
System.out.println("The Number is "+test);

The output of the above snippet of code will be

The Number is 1020


Planning to write more such very small posts that can be used a quick reference.

Happy Working....