publicclassTurtle{privateStringname;privateFormatterf;publicTurtle(Stringname,Formatterf){this.name=name;this.f=f;}publicvoidmove(intx,inty){f.format("%s The Turtle is at (%d,%d)\n",name,x,y);}publicstaticvoidmain(String[]args){PrintStreamoutAlias=System.out;Turtletommy=newTurtle("Tommy",newFormatter(System.out));Turtleterry=newTurtle("Terry",newFormatter(outAlias));tommy.move(0,0);terry.move(4,8);tommy.move(3,4);terry.move(2,5);tommy.move(3,3);terry.move(3,3);}}/*Tommy The Turtle is at (0,0)Terry The Turtle is at (4,8)Tommy The Turtle is at (3,4)Terry The Turtle is at (2,5)Tommy The Turtle is at (3,3)Terry The Turtle is at (3,3) */
publicclassSplitting{publicstaticStringknights="Then, when you have found the shrubbery, you must "+"cut down the mightiest tree in the forest... "+"with... a herring!";publicstaticvoidsplit(Stringregex){System.out.println(Arrays.toString(knights.split(regex)));}publicstaticvoidmain(String[]args){split(" ");split("\\W+");//非单词字符split("n\\W+");//n后面跟着一个或多个非单词字符}}/*[Then,, when, you, have, found, the, shrubbery,, you, must, cut, down,the, mightiest, tree, in, the, forest..., with..., a, herring!][Then, when, you, have, found, the, shrubbery, you, must, cut, down,the, mightiest, tree, in, the, forest, with, a, herring][The, whe, you have found the shrubbery, you must cut dow, the mightiest tree i, the forest... with... a herring!] */
publicclassGroups{staticpublicfinalStringPOEM="Twas brillig, and the slithy toves\n"+"Did gyre and gimble in the wabe.\n"+"All mimsy were the borogoves,\n"+"And the mome raths outgrabe.\n\n"+"Beware the Jabberwock, my son,\n"+"The jaws that bite, the claws that catch.\n"+"Beware the Jubjub bird, and shun\n"+"The frumious Bandersnatch.";publicstaticvoidmain(String[]args){Matcherm=Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM);while(m.find()){for(inti=0;i<=m.groupCount();i++){System.out.print("["+m.group(i)+"]");}System.out.println();}}}/*[the slithy toves][the][slithy toves][slithy][toves][in the wabe.][in][the wabe.][the][wabe.][were the borogoves,][were][the borogoves,][the][borogoves,][mome raths outgrabe.][mome][raths outgrabe.][raths][outgrabe.][Jabberwock, my son,][Jabberwock,][my son,][my][son,][claws that catch.][claws][that catch.][that][catch.][bird, and shun][bird,][and shun][and][shun][The frumious Bandersnatch.][The][frumious Bandersnatch.][frumious][Bandersnatch.] */
publicclassStartEnd{publicstaticStringinput="As long as there is injustice, whenever a\n"+"Targathian baby cries out, wherever a distress\n"+"signal sounds among the stars... We'll be there.\n"+"This fine ship, and this fine crew ...\n"+"Never give up! Never surrender!";privatestaticclassDisplay{privatebooleanregexPrinted=false;privateStringregex;Display(Stringregex){this.regex=regex;}voiddisplay(Stringmessage){if(!regexPrinted){System.out.println(regex);regexPrinted=true;}System.out.println(message);}}staticvoidexamine(Strings,Stringregex){Displayd=newDisplay(regex);Patternp=Pattern.compile(regex);Matcherm=p.matcher(s);while(m.find()){d.display("find() '"+m.group()+"' start = "+m.start()+" end = "+m.end());}if(m.lookingAt()){d.display("lookingAt() start = "+m.start()+" end = "+m.end());}if(m.matches()){d.display("matches() start = "+m.start()+" end = "+m.end());}}publicstaticvoidmain(String[]args){for(Stringin:input.split("\n")){System.out.println("input : "+in);for(Stringregex:newString[]{"\\w*ere\\w*","\\w*ever","T\\w+","Never.*?!"}){examine(in,regex);}}}}/*input : As long as there is injustice, whenever a\w*ere\w*find() 'there' start = 11 end = 16\w*everfind() 'whenever' start = 31 end = 39input : Targathian baby cries out, wherever a distress\w*ere\w*find() 'wherever' start = 27 end = 35\w*everfind() 'wherever' start = 27 end = 35T\w+find() 'Targathian' start = 0 end = 10lookingAt() start = 0 end = 10input : signal sounds among the stars... We'll be there.\w*ere\w*find() 'there' start = 42 end = 47input : This fine ship, and this fine crew ...T\w+find() 'This' start = 0 end = 4lookingAt() start = 0 end = 4input : Never give up! Never surrender!\w*everfind() 'Never' start = 0 end = 5find() 'Never' start = 15 end = 20lookingAt() start = 0 end = 5Never.*?!find() 'Never give up!' start = 0 end = 14find() 'Never surrender!' start = 15 end = 31lookingAt() start = 0 end = 14matches() start = 0 end = 31 */
publicclassReFlags{publicstaticvoidmain(String[]args){Patternp=Pattern.compile("^java",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);Matcherm=p.matcher("java has regex\nJava has regex\n"+"JAVA has pretty good regular expressions\n"+"Regular expressions are in Java");while(m.find()){System.out.println(m.group());}}}/*javaJavaJAVA */
/*!Here's a block of text to use as input to the regular expression matcher. Note that we'll first extract the block of text by looking for the special delimiters, then process the extracted block. !*/importnet.mindview.util.TextFile;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassTheReplacements{publicstaticvoidmain(String[]args){Strings=TextFile.read("src/main/java/strings/TheReplacements.java");MatchermInput=Pattern.compile("/\\*!(.*)!\\*/",Pattern.DOTALL).matcher(s);if(mInput.find()){s=mInput.group(1);}//将存在两个或两个以上空格的地方,缩减为一个空格,并且s=s.replaceAll(" {2,}"," ");//删除每行开头部分的所有空格s=s.replaceAll("(?m)^ +","");System.out.println(s);//replaceFirst只对找到的第一个匹配进行替换s=s.replaceFirst("[aeiou]","(VOWEL1)");StringBuffersbuf=newStringBuffer();Patternp=Pattern.compile("[aeiou]");Matcherm=p.matcher(s);while(m.find()){m.appendReplacement(sbuf,m.group().toUpperCase());}System.out.println(sbuf);m.appendTail(sbuf);System.out.println(sbuf);}}/*Here's a block of text to use as input tothe regular expression matcher. Note that we'llfirst extract the block of text by looking forthe special delimiters, then process theextracted block.H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tOthE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'llfIrst ExtrAct thE blOck Of tExt by lOOkIng fOrthE spEcIAl dElImItErs, thEn prOcEss thEExtrActEd blOH(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tOthE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'llfIrst ExtrAct thE blOck Of tExt by lOOkIng fOrthE spEcIAl dElImItErs, thEn prOcEss thEExtrActEd blOck. */
publicclassResetting{publicstaticvoidmain(String[]args){Matcherm=Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");while(m.find()){System.out.print(m.group()+" ");}System.out.println();m.reset("fix the rig with rags");while(m.find()){System.out.print(m.group()+" ");}}}
publicclassSimpleRead{publicstaticBufferedReaderinput=newBufferedReader(newStringReader("Sir Robin of Camelot \n22 1.61803"));publicstaticvoidmain(String[]args){try{System.out.println("What is your name?");Stringname=input.readLine();System.out.println(name);System.out.println("How old are you? What is your favorite double?");System.out.println("(input: <age> <double>)");Stringnumbers=input.readLine();System.out.println(numbers);String[]numArray=numbers.split(" ");intage=Integer.parseInt(numArray[0]);doublefavorite=Double.parseDouble(numArray[1]);System.out.format("Hi %s.\n",name);System.out.format("In 5 years you will be %d.\n",age+5);System.out.format("My favorite double is %f.",favorite/2);}catch(IOExceptione){System.out.println("I/O exception");}}}/*What is your name?Sir Robin of CamelotHow old are you? What is your favorite double?(input: <age> <double>)22 1.61803Hi Sir Robin of Camelot .In 5 years you will be 27.My favorite double is 0.809015. */
publicclassBetterRead{publicstaticvoidmain(String[]args){Scannerstdin=newScanner(SimpleRead.input);System.out.println("What is your name?");Stringname=stdin.nextLine();System.out.println(name);System.out.println("How old are you? What is your favorite double?");System.out.println("input: <age> <double>");intage=stdin.nextInt();doublefavorite=stdin.nextDouble();System.out.format("Hi %s.\n",name);System.out.format("In 5 years you will be %d.\n",age+5);System.out.format("My favorite double is %f.",favorite/2);}}/*What is your name?Sir Robin of CamelotHow old are you? What is your favorite double?input: <age> <double>Hi Sir Robin of Camelot .In 5 years you will be 27.My favorite double is 0.809015. */
publicclassThreatAnalyzer{staticStringthreatData="58.27.82.161@02/10/2005\n"+"204.45.234.40@02/11/2005\n"+"58.27.82.161@02/11/2005\n"+"58.27.82.161@02/12/2005\n"+"58.27.82.161@02/12/2005\n"+"[Next log section with different data format]";publicstaticvoidmain(String[]args){Scannerscanner=newScanner(threatData);Stringpattern="(\\d+[.]\\d+[.]\\d+[.]\\d+)@"+"(\\d{2}/\\d{2}/\\d{4})";while(scanner.hasNext(pattern)){scanner.next(pattern);MatchResultmatch=scanner.match();Stringip=match.group(1);Stringdate=match.group(2);System.out.format("Threat on %s from %s\n",date,ip);}}}/*Threat on 02/10/2005 from 58.27.82.161Threat on 02/11/2005 from 204.45.234.40Threat on 02/11/2005 from 58.27.82.161Threat on 02/12/2005 from 58.27.82.161Threat on 02/12/2005 from 58.27.82.161 */
publicclassReplacingStringTokenizer{publicstaticvoidmain(String[]args){Stringinput="But I'm not dead yet! I feel happy!";StringTokenizerstoke=newStringTokenizer(input);while(stoke.hasMoreElements()){System.out.print(stoke.nextToken()+" ");}System.out.println();System.out.println(Arrays.toString(input.split(" ")));Scannerscanner=newScanner(input);while(scanner.hasNext()){System.out.print(scanner.next()+" ");}}}/*But I'm not dead yet! I feel happy![But, I'm, not, dead, yet!, I, feel, happy!]But I'm not dead yet! I feel happy! */