stock quote

7/22/09

about writing regular expression in Java

If only want to match one string once,
use:
String myPatternStr = "a*b";
boolean b = Pattern.matches(myPatternStr, "aaaaab");

If need to match multiple times, then need to use:
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
See the complimentary tutorial at sun:
http://java.sun.com/docs/books/tutorial/essential/regex/index.html

For recognizing some special characters like "\d","\s", we actually need "\\":
This is because the Java core syntax will be applied first, then the reg expression special char syntax.
So if you want to find a match for "a*" (a followed by a literal star), you should write:
String patternStr = "a\\*"; not "a*"(means zero or more a); not "a\*" (because Java syntax will try to parse "\*" as a special char and the "\" as an escape symbol)
and for matching a literal backslash, we need "\\\\" in our program

http://www.javamex.com/tutorials/regular_expressions/character_classes_named.shtml
http://www.scribd.com/doc/965568/16-Java-Regex

Greedy and none greedy string match: (add "?" after the char that is not requiring strict matching)
http://www.exampledepot.com/egs/java.util.regex/Greedy.html?l=rel

Don't forget the regular expression standard, no mater which language you're using.
http://regexlib.com/CheatSheet.aspx