很幸運地參加了這次考試,因爲這個第三題對我這麼一個愛正則的人來說,太順手了。沒錯,拿到滿分全靠運氣🌚
<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);
}
}
}