1. Get the three-character word in the following string.
Da Jia Ting wo shuo,jin tian Yao xia yu,bu Shang wan zi Xi,gao xing bu?
2. Code implementation:
1 Packagecn.itcast_05;2 3 ImportJava.util.regex.Matcher;4 ImportJava.util.regex.Pattern;5 6 /*7 * Get Features:8 * Get a three-character word from the following string9 * da Jia Ting wo shuo,jin tian Yao xia yu,bu Shang wan zi Xi,gao xing bu?Ten */ One Public classRegexDemo2 { A Public Static voidMain (string[] args) { - //Defining Strings -String s = "da Jia ting wo shuo,jin tian Yao xia yu,bu Shang wan zi Xi,gao xing bu?"; the //rules -String regex = "\\b\\w{3}\\b"; - - //compiling the rules into a schema object +Pattern p =pattern.compile (regex); - //getting a Match object from a pattern object +Matcher m =P.matcher (s); A //the ability to invoke a match object at //the Find method is to look for substrings that have not met the criteria - //Public Boolean find () - //Boolean flag = M.find (); - //System.out.println (flag); - // //How do I get a value ? - // //Public String Group () in //String ss = M.group (); - //SYSTEM.OUT.PRINTLN (ss); to // + // //one more time. - //flag = M.find (); the //System.out.println (flag); * //ss = M.group (); $ //SYSTEM.OUT.PRINTLN (ss);Panax Notoginseng - while(M.find ()) { the System.out.println (M.group ()); + } A the //Note: Be sure to first find () before group () + //Illegalstateexception:no match found - //String ss = M.group (); $ //SYSTEM.OUT.PRINTLN (ss); $ } -}
The results are as follows:
Java Fundamentals Hardening 79: The acquisition of regular expressions (case)