Studyon Minte9.com
Regexp




Pattern



* Pattern

	%java
		import java.util.regex.*;
		...

		Pattern pat = Pattern.compile("Java");
		Matcher mat = pat.matcher("Java");
		boolean found = mat.matches();
		
		System.out.println(mat);
		    // Output: java.util.regex.Matcher[pattern=Java region=0,4 lastmatch=Java]
		System.out.println(found);
		    // Output: true

* Find

	Remember, matches() returns true only when preciseley matches the pattern. 
	You can use find() for sebsecquence.

	%java
		Pattern pat = Pattern.compile("Java");
		Matcher mat = pat.matcher("Java SE 6");
		boolean found = mat.matches();
		
		System.out.println(mat.matches());
		    // Output: false
		System.out.println(mat.find());
		    // Output: true

* Start

	You can used find() for repeated occurrences of the pattern

	%java
		Pattern pat = Pattern.compile("test");
		Matcher mat = pat.matcher("test 5 7 9 test");
		
		while(mat.find()) {
		    System.out.println("index: " + mat.start());
			// index: 0
			// index: 11
		}

* Wildcards and Quantifiers
	
	%java
		Pattern pat = Pattern.compile("W+");
		Matcher mat = pat.matcher("W WW WWW");
		
		while(mat.find()) {
		    System.out.println("Match: " + mat.group());
			// Match: W
			// Match: WW
			// Match: WWW
		}

	%java
		// Greedy
		Pattern pat = Pattern.compile("e.+d");
		Matcher mat = pat.matcher("extend cup end table");
		
		while(mat.find()) {
		    System.out.println("Match: " + mat.group());
			// Match: extend cup end
		}

	You might have expect two matches: "extend" and "end"
	This is call "greedy behavior" which match the longest sequence.
	You can specify "reluctant behavior" by adding "?" quantifier.

	%java
		// Ungreedy
		Pattern pat = Pattern.compile("e.+?d");
		Matcher mat = pat.matcher("extend cup end table");
		
		while(mat.find()) {
		    System.out.println("Match: " + mat.group());
			// extend
			// end
		}



* Classes and Characters

	%java
		Pattern pat = Pattern.compile("[a-z]+");
		Matcher mat = pat.matcher("this is a test");
		
		while(mat.find()) {
		    System.out.println("Match: " + mat.group());
			// this
			// is
			// a
			// test
		}

* Escape Chars

	%java
		                // [Why not call it] the Big Chill?
		Pattern pat = Pattern.compile(Pattern.quote("[") + "[ a-zA-z]+" + Pattern.quote("]"));
		Matcher mat = pat.matcher(sEn);
		if (mat.find()) {
			wEn = mat.group().replace("[", "").replace("]", "");
			sEn = sEn.replace("[", "").replace("]", "");
		}


http://stackoverflow.com/questions/60160/how-to-escape-text-for-regular-expression-in-java
http://www.java2s.com/Code/Java/Regular-Expressions/Pattern.htm