0%

第十次CSP认证 T3-Markdown(正则表达式+字符串处理)

题目链接

看了大佬的正则表达式解法, 值得学习一下

AcWing 3244. Markdown - 正则表达式解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;

string patt1("#+");
string patt2("_(.+?)_");
string patt3("\\[(.+?)\\]\\((.+?)\\)");

regex r1(patt1);
regex r2(patt2);
regex r3(patt3);

string deal (string s) {
while(s[0] == ' ') s.erase(s.begin());
s = regex_replace(s, r2, "<em>$1</em>");
s = regex_replace(s, r3, "<a href=\"$2\">$1</a>");
return s;
}

int main() {
string line;
int tap = 0, flag = 1;
while(getline(cin, line)) {
if(line == "") {
if(flag == 0 && tap == 2) {
cout << "</ul>" << endl;
}else if(flag == 0 && tap == 3) cout << "</p>" << endl;
flag = 1;
} else {
stringstream ssin(line);
string s;
ssin >> s;
if(regex_match(s, r1)) {
int a = s.size();
getline(ssin, s);
s = deal(s);
cout << "<h" << a << ">" << s << "</h" << a << ">" << endl;
tap = 1;
} else if(s == "*") {
if(flag) {
cout << "<ul>" << endl;
}
getline(ssin, s);
s = deal(s);
cout << "<li>" << s << "</li>" << endl;
tap = 2;
} else {
if(flag) cout << "<p>";
else cout << endl;
string s2;
getline(ssin, s2);
s = s + s2;
cout << deal(s);
tap = 3;
}
flag = 0;
}
}
if(flag == 0 && tap == 2) cout << "</ul>" << endl;
else if(flag == 0 && tap == 3) cout << "</p>" << endl;

return 0;
}
求大佬赏个饭