View RSS Feed

Java String

Java Pattern Class

Rate this Entry
by , 04-26-2012 at 06:54 PM (560 Views)
Pattern class instance presents the regular expression which has been specified in string form, in syntax, same as used by Perl.

Regular expression shall be compiling first to the Pattern class instance. Matcher object is created by ther resulting pattern, which matches with the sequence of the arbitrary character. Similar patterns are shared by various matchers as it is stateless.

Given regular expression is compiled by the compile method into a pattern. After this, matcher is created by the matcher method which matches to the given input, against pattern. Regular expression is returned by the pattern method, from which pattern got compiled.

Split method is considered as a convenience method which makes the given input sequence to be split around this pattern’s matches.
Java Code:
import java.util.regex.*;

public class Splitter {
    public static void main(String[] args) throws Exception {
        // Create a pattern to match breaks
        Pattern p = Pattern.compile("[,\\s]+");
        // Split input with the pattern
        String[] result = 
                 p.split("one,two, three   four ,  five");
        for (int i=0; i<result.length; i++)
            System.out.println(result[i]);
    }
}

Submit "Java Pattern Class" to Facebook Submit "Java Pattern Class" to Digg Submit "Java Pattern Class" to del.icio.us Submit "Java Pattern Class" to StumbleUpon Submit "Java Pattern Class" to Google

Categories
Regex

Comments