Understanding the boundary of java-11.5 Scanning Input from scratch (2)-embedding and scanning using regular expressions
In this section, we will introduce the boundary of limit and the use of regular expressions for scanning.
1. Border of a shard
In the previous chapter, we mentioned that the hasNext method in the delimiter can be used to check whether there are any strings. In fact, this is the boundary character and 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(raylee311.77));public 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. Scan using regular expressions
In many cases, we need to scan and collect statistics on logs. Generally, logs are recorded in a txt file. In this case, the matching of regular expressions and operators is quite efficient, let's 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(127.0.0.1@admin@2015-12-01 + 127.0.0.2@ray@2015-12-03+ 127.0.0.31@rose@2015-12-05+ 127.0.0.41@jack@2015-12-07 + end));public 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-3 3
Ip: 127.0.0.31
User: rose
Date: 2015-5 5
Ip: 127.0.0.41
User: jack
Date: 2015-12-07
In the above Code, it is very important to note the writing of regular expressions, especially several parentheses, because strings can be grouped through several parentheses. If no parentheses exist, the group (1) group (2) following the parentheses will throw an exception.
Summary: This chapter briefly describes the boundary of the operator and the use of regular expressions for scanning.