In this chapter we introduce the boundary of scanner and the use of regular expression scans.
Boundary of 1.scanner
In the previous chapter, we mentioned that there are hasnext methods in scanner, which can detect if there are strings, in fact, this is the boundary character, check the boundary of the string.
Package Com.ray.ch11;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.stringreader;import Java.util.scanner;public class Test {private BufferedReader input = new BufferedReader (new StringReader ("raylee\n31\ n1.77 "));p ublic BufferedReader getinput () {return input;} public void SetInput (BufferedReader input) {this.input = input;} public static void Main (string[] args) throws IOException {test test = new Test (); Scanner Scanner = new Scanner (Test.getinput ()), while (Scanner.hasnext ()) {System.out.println (Scanner.nextline ());}}}
Output:
Raylee
31
1.77
2. Using regular expression scanning
A lot of time we need to scan and statistics log situation, and the general log is recorded in a TXT file, then this time the regular expression and scanner of the match is quite efficient, we look at the following code:
Package Com.ray.ch11;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.stringreader;import Java.util.scanner;import Java.util.regex.matchresult;import Java.util.regex.pattern;public class Test {private BufferedReader input = new BufferedReader (New StringReader ("[email protected]@2015-12-01\n" + "[email protected]@2015-12-03\n "+" [email protected]@2015-12-05\n "+" [email protected]@2015-12-07\n "+" end\n ")) ;p ublic BufferedReader getinput () {return input;} public void SetInput (BufferedReader input) {this.input = input;} public static void Main (string[] args) throws IOException {test test = new Test (); Scanner Scanner = new Scanner (Test.getinput ()); Pattern pattern = Pattern.compile ("(\\d+[.) \\d+[.] \\d+[.] \\d+) "+" @ "+" ([a-z]+) + "@" + "(\\d{4}-\\d{2}-\\d{2})"), while (Scanner.hasnext (pattern)) {Scanner.next (pattern); Matchresult Matchresult = Scanner.match (); System.out.println ("IP:" +matchresult.group (1)); System.out.println ("User:" +matchresult.group (2)); System.out.println ("Date:" +matchresult.group (3));}}}
Output:
ip:127.0.0.1
User:admin
Date:2015-12-01
ip:127.0.0.2
User:ray
date:2015-12-03
ip:127.0.0.31
User:rose
date:2015-12-05
ip:127.0.0.41
User:jack
date:2015-12-07
In the above code there is a very important place to note is the writing of regular expressions, especially a few parentheses, because the string can be grouped by a few parentheses. If there are no parentheses, the following group (1) Group (2) will throw an exception.
Summary: This chapter simply describes the boundary of the scanner and the use of regular expression scans.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-11.5 Scan Input (2)-scanner boundary and using regular expression scan