Java-Character Classes

Character Classes

Regular expression languages also have character classes, which are a way of specifying a list of possible characters that can match any single character in the string you want to match. If you want to specify a character class explicitly, the characters go between square brackets. Therefore, the character class [0123456789] matches any single digit. It is also possible to specify “any character except one of these” by using the caret after the first square bracket. Using the expression [^012], any single digit except for 0, 1, and 2 is matched. You can specify character ranges using the dash. The character class [a-z] matches any single lowercase letter, and [^a-z] matches any character except a lowercase letter. Any character range can be used, such as [0–9] to match a single digit, or [0–3] to match a 0, 1, 2, or 3. Multiple ranges can be specified, such as [a-zA-Z] to match any single letter.

Program One

 

Program Two

 

Program Three

 

Program Four



Program One Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[2468Z]");
        Matcher mat = pat.matcher("1234545678Z");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Program Two Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[2-8][A-F]");
        Matcher mat = pat.matcher("1C2B3X4A9G5D6Y");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Program Three Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("[^ABC]");
        Matcher mat = pat.matcher("ABCDEFab123");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Program Four Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("A[GXT]E");
        Matcher mat = pat.matcher("AGE AZE AXE AQE ATE");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Leave a Comment