Regular Expression
Video:
Character Classes
[abc] – either a , b or c
[^abc] – except a, b, c
[a-z] – any lower case alphabet symbol from a to z
[A-Z] – any lower case alphabet symbol from A to Z
[0-9] – Any digit from 0 to 9
[a-zA-Z] = Any alphabet
[0-9] – Any digit from 0 to 9
[0-9a-zA-Z] = Any alphanumeric symbols
[^0-9a-zA-Z] = Special symbol except alphanumeric symbols
Pre-defined Character Classes
\s – Space character
\S – Expect Space character
\d = Any digit from 0 to 9 [0-9]
\D = Except digit, any character
\w = Any word character [0-9a-zA-Z]
\W = Except word character [special character]
. = Any character
Quantifiers – We can use quantifiers to specify the number of occurrences to match
a = Exactly one ‘a’
a+ = atleast one ‘a’
a* = Any number a’s including zero number
a? = Almost one ‘a’
Java Example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class CharacterClasses { public static void main(String[] args) { String text = "a3b#K@9Z "; int count = 0; Pattern p = Pattern.compile("[0-9]"); Matcher m = p.matcher(text); while(m.find()) { count++; System.out.println(m.start()+" "+ m.end()+" "+m.group()); } System.out.println("The total number of occurences is "+count); } } |