In this Java example we are going to learn How to Check Special Characters in Java Code,
so a special character is a character that is not an alphabetic or numeric character. Punctuation
marks and other symbols are examples of special charecters like @, #, $, %, &. you can simply
use regex class for doing this.especially we are going to use java.util.regex.Matcher and
java.util.regex.Pattern. so Java Matcher class is used to search through a text for multiple
occurrences of a regular expression. You can also use a Matcher to search for the same
regular expression in different texts.
Also you can check Java GUI Development with JavaFX
1: JavaFX GUI Development Tutorials
So now this is the code for How to Check Special Characters in Java Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Codeloop { public static void main(String[] args) { // TODO Auto-generated method stub String text = "@codeloop#"; Pattern pattern = Pattern.compile("[^A-Za-z0-9]"); Matcher matcher = pattern.matcher(text); boolean match = matcher.find(); if (match == true) System.out.println("Text contains special charecter : " + text); else System.out.println( "Text does not contain special charecter " + text); } } |
So you can see that after creating of our java class (Codeloop), we have imported our required
classes from regex. basically we need two imports java.util.regex.Matcher and
java.util.regex.Pattern.
In here we have created our Pattern . and after that we have defined our pattern.
1 |
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]") |
And in here we have created our Matcher.
1 |
Matcher matcher = pattern.matcher(text); |
Now if you run the code this will be the result.
1 |
Text contains special charecter : @codeloop# |
So let’s remove the special character from our text, and this will be the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Codeloop { public static void main(String[] args) { // TODO Auto-generated method stub String text = "codeloop"; Pattern pattern = Pattern.compile("[^A-Za-z0-9]"); Matcher matcher = pattern.matcher(text); boolean match = matcher.find(); if (match == true) System.out.println("Text contains special charecter : " + text); else System.out.println( "Text does not contain special charecter " + text); } } |
Result :
1 |
Text does not contain special charecter codeloop |
Subscribe and Get Free Video Courses & Articles in your Email