Regex Character Classes with example

Regex Character Classes :

[abc] : a,b or c characters only

[^abc] : Any character except a, b or c character.

[a-zA-Z] : a through z or A through Z, inclusive range.

[a-d[m-p]] : a through d or m through p

[a-z&&[def]] : d, e or f intersection.

[a-z&&[^bc]] : a through z except b and c

[a-z&&[^m-p]] : a through z and not m through p


4. Regex qualifiers :

X? : X occurs once or not at all.

X+ : X occurs once or more times.

X* : X occurs 0 or more times.

X{n} : X occurs n times only.

X{n,} : X occurs n or more times.

X{y,z} : X occurs at least y times but leass than z times.

import java.util.regex.*;

class RegexExample4{
public static void main(String args[]){

System.out.println("? quantifier ....");
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)

System.out.println("+ quantifier ....");
System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)
System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)
System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)
System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)

System.out.println("* quantifier ....");
System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more times)

}

Share this

Related Posts

Previous
Next Post »