Map解法
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rule_count = scanner.nextInt();
int url_count = scanner.nextInt();
scanner.nextLine();
Map<String,String> map = new LinkedHashMap<>();
for(int i = 0; i < rule_count; i++){
String rule = scanner.nextLine();
String[] arr = rule.split(" ");
String regex = arr[0];
regex = regex.replace("<int>","([0-9]+)");
regex = regex.replace("<str>", "([^/]+)");
regex = regex.replace("<path>","(.+)");
map.put(arr[1],regex);
}
for(int i = 0; i < url_count;i++){
String line = scanner.nextLine();
boolean bFind = false;
for(Map.Entry<String,String> entry : map.entrySet()){
Pattern pattern = Pattern.compile(entry.getValue());
Matcher matcher = pattern.matcher(line);
if(matcher.matches()){
bFind = true;
System.out.print(entry.getKey()+" ");
for(int j = 1; j <= matcher.groupCount(); j++){
String tmp = matcher.group(j);
if(tmp.matches("[0-9]+")){
System.out.print(Integer.parseInt(tmp)+" ");
}
else{
System.out.print(tmp+" ");
}
}
break;
}
}
if(!bFind){
System.out.print("404");
}
System.out.println();
}
}
}
另一种解法
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class RegexInfo{
String regex;
String name;
public RegexInfo(String regex, String name) {
this.regex = regex;
this.name = name;
}
}
public class Main7 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
scanner.nextLine();
List<RegexInfo> regexInfoList = new ArrayList<>();
for(int i = 0; i < n; i++){
String line = scanner.nextLine();
String[] arr = line.split(" ");
String regex = arr[0].replaceAll("<int>", "([0-9]+)");
regex = regex.replaceAll("<str>","([^/]+)");
regex = regex.replaceAll("<path>","(.+)");
RegexInfo regexInfo = new RegexInfo(regex, arr[1]);
regexInfoList.add(regexInfo);
}
for(int i = 0; i < m; i++){
String line = scanner.nextLine();
boolean bFind = false;
for(int j = 0; j < regexInfoList.size(); j++){
RegexInfo regexInfo = regexInfoList.get(j);
Pattern pattern = Pattern.compile(regexInfo.regex);
Matcher matcher = pattern.matcher(line);
if(matcher.matches()){
System.out.print(regexInfo.name);
for(int k = 1; k <= matcher.groupCount(); k++){
String info = matcher.group(k);
if(info.matches("[0-9]+")){
int value = Integer.parseInt(info);
System.out.print(" " + value);
}
else{
System.out.print(" " + info);
}
}
bFind = true;
System.out.println();
break;
}
}
if(!bFind){
System.out.println("404");
}
}
}
}