正则表达式的版本,可以简化部分字符串匹配的问题,代码更加精简
C++ 代码
//3.URL映射
#include<bits/stdc++.h>
using namespace std;
string patt1("/[0]*([0-9]+)");
string patt2("/([0-9a-zA-Z_\\.-]+)");
string patt3("(/[0-9a-zA-Z_\\.-]+)");
string patt4("(/[0-9a-zA-Z_\\.-]*)");
string patt5("/[0]+");
regex r1(patt1);
regex r2(patt2);
regex r3(patt3);
regex r4(patt4);
regex r5(patt5);
int n, m;
string parm;
vector<string> to_vec(string s){
vector<string> v;
for(int i = 0, j = 1; j <= s.size(); ++ j){
if(j == s.size() || s[j] == '/'){
v.push_back(s.substr(i, j - i));
i = j;
}
}
return v;
}
bool cmp(string s1, string s2){
if(s1 == "/<int>"){
smatch res;
if(regex_match(s2, res, r5)){
parm += " 0";return true;
}
else if(regex_match(s2, res, r1)){
parm += ' '; parm += res[1]; return true;
}
else return false;
}
else if(s1 == "/<str>"){
smatch res;
if(regex_match(s2, res, r2)){
parm += ' '; parm += res[1]; return true;
}
else return false;
}
else{
return s1 == s2;
}
}
struct Rule{
vector<string> r;
string name;
Rule(string s, string nm){
name = nm;
r = to_vec(s);//to_vec
}
bool is_fit(vector<string> v){
parm = "";
int i;
if(v.size() < r.size()) return false;
for(i = 0; i < r.size(); ++ i){
if(r[i] == "/<path>"){
if(i == v.size() - 1 && v[i] == "/") return false;
string s = "";
parm += ' ';
while(i < v.size() - 1){
if(regex_match(v[i], r3)){
s += v[i];
i ++;
}
else{
parm = "";
return false;
}
}
if(regex_match(v[i], r4)) s += v[i];
else{
parm = ""; return false;
}
parm += s.substr(1,s.size() - 1);
}
else{
if(!cmp(r[i], v[i])) {
parm = ""; return false;
}
}
}
if(i != v.size()) {
parm = ""; return false;
}
cout << name << parm << endl;
parm = "";
return true;
}
};
int main(){
cin >> n >> m;
vector<Rule> rule;
for(int i = 0; i < n; ++ i){
string s1, s2;
cin >> s1 >> s2;
rule.push_back(Rule(s1, s2));
}
while(m --){
string s1;
cin >> s1;
vector<string> v(to_vec(s1));//to_vec
int i;
for(i = 0; i < n; ++ i){
if(rule[i].is_fit(v)) break;
}
if(i == n) cout << "404" << endl;
}
return 0;
}
# 但貌似还是比我没用正则的多12行(
awa
# 但你不知道他和你的不是一个语言吗(