Remove All Unwanted Characters from String in Java

[9342 views]




Remove All Unwanted Characters from String in Java

Strings are widely used in Java programming language, which are a sequence of characters. The Java platform provides the String class to create and manipulate strings. String is mostly used to store text data.

But String can contain various characters like $, &, @,!,(whitespace),* and many more which when used to perform some Business logic operations can create issues like inserting such String into Database will create issues. So, if you want to remove those unwanted characters, here is a simple program in java which uses regular expresssion to remove unwanted characters.

Example: Test.java

public class Test { public static void main(String[] args) { String text = "This $ is @ a sentence"; text = text.replaceAll("[^a-zA-Z0-9]", ""); System.out.println(text); } }

Output

Thisisasentence

In above Java Program, we have used this regular expression:

[^a-zA-Z0-9]
The meaning of this regular expression is "All characters other than capital A to Z, small A to Z and number 0 to 9".

                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?



Comments










Search

Hot Deals ends in













Technical Quizzes Specially For You:

Search Tags

    Remove $ from string using java

    remove white spaces from string using java

    Java code to remove special character from String