很幸运地参加了这次考试,因为这个第三题对我这么一个爱正则的人来说,太顺手了。没错,拿到满分全靠运气?
<int> 对应的正则是 [0-9]+
<str> 对应的正则是[a-zA-Z0-9\\-_\\.]+
<path> 对应的正则是[a-zA-Z0-9\\-_\\./]+,相比str多了/
使用pattern.matcher对匹配的参数进行输出,另外还需要一个List来记录当前规则是不是int,若是int,要将匹配内容转化为int(即去掉前导零的操作)
奉上java满分代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
static class UrlRegex {
public String regex;
public String name;
public List<Boolean> isInt;
public Pattern pattern;
public UrlRegex(String line) {
String[] data = line.split(" ");
this.name = data[1];
this.isInt = new ArrayList<>();
String[] parts = data[0].split("/");
StringBuffer stringBuffer = new StringBuffer();
for (String part : parts) {
if (part.length() == 0)
continue;
stringBuffer.append("/");
if (part.equals("<int>")) {
stringBuffer.append("([0-9]+)");
isInt.add(true);
} else if (part.equals("<str>")) {
stringBuffer.append("([a-zA-Z0-9\\-_\\.]+)");
isInt.add(false);
} else if (part.equals("<path>")) {
stringBuffer.append("([a-zA-Z0-9\\-_\\./]+)");
isInt.add(false);
} else {
stringBuffer.append(part);
}
}
if (data[0].endsWith("/"))
stringBuffer.append("/");
this.regex = stringBuffer.toString();
this.pattern = Pattern.compile(this.regex);
}
}
public static void main(String[] args) {
List<UrlRegex> urlRegexList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String[] firstLine = scanner.nextLine().split(" ");
int n = Integer.parseInt(firstLine[0]);
int m = Integer.parseInt(firstLine[1]);
for (int i = 0; i < n; i++) {
urlRegexList.add(new UrlRegex(scanner.nextLine()));
}
List<String> urls = new ArrayList<>();
for (int i = 0; i < m; i++) {
urls.add(scanner.nextLine());
}
scanner.close();
Matcher matcher;
for (String url : urls) {
boolean found = false;
for (UrlRegex urlRegex : urlRegexList) {
if(url.matches(urlRegex.regex)) {
System.out.print(urlRegex.name);
matcher = urlRegex.pattern.matcher(url);
if (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
String content = matcher.group(i);
if (urlRegex.isInt.get(i - 1))
content = String.valueOf(Integer.parseInt(content));
System.out.print(" " + content);
}
System.out.println();
}
found = true;
break;
}
}
if (!found)
System.out.println(404);
}
}
}