Summary On Java Expression
Summary On Java Expression
\d : Represents a digit.
\D : Represents a non-digit
\s : Represents a whitespace.
\S : Represents a non-whitespace
\w : Represents a word Character
(letters, numbers or an underscore).
\W : Represents a non-word Character.
“.” : Represents any character
The basic structure of a RegEx is bounded by the below
mentioned classes.
Literal escape \x
Grouping [...]
Range a-z
Union [a-e][i-u]
Intersection [a-z&&[aeiou]]
1. Pattern class
2. Matcher class
(Both the classes are present in the java.util.regex
package)
A regular expression, specified as a string, must first
be compiled into an instance of this class.
Output:
0 6 aaaaab
import java.util.regex.*;
public class Regex
{
public static void main(String[] arg)
{
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("b aab");
if(m.lookingAt())
System.out.println(m.start()+" "+m.end()+" "+m.group());
}
}
Output:
0 1 b
import java.util.regex.*;
public class Regex
{
public static void main(String[] arg)
{
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("ab aabcba");
while(m.find())
System.out.println(m.start()+" "+m.end()+" "+m.group());
}
}
Output:
0 2 ab
3 6 aab
7 8 b
Writing the statement:
String regex=“\d”;
would produce a COMPILER ERROR!
String regex=“\\d”;
is a valid RegEx metacharacter in the form of a String.
Suppose, if we want the dot (.) to represent its usual meaning
while writing a Regular Expression as a String.
String s=“\\.”;
Represents a dot, and not some RegEx metacharacter.
Java api documentation SE6
SCJP – Kathy Sierra and Bert Bates
Wikipedia