实践周3
1 #include <bits/stdc++.h> 2 #include <regex> 3 using namespace std; 4 int main() 5 { 6 int n; 7 scanf("%d", &n); 8 getchar(); 9 while(n--) 10 { 11 string s; 12 getline(cin, s); 13 cout << s << endl; 14 s = regex_replace(s, regex(R"(\s+)"), " "); 15 if(s.front() == ' ') s.erase(s.begin()); 16 if(s.back() == ' ') s.pop_back(); 17 s = regex_replace(s, regex(R"( !)"), "!"); 18 s = regex_replace(s, regex(R"( ,)"), ","); 19 s = regex_replace(s, regex(R"( \.)"), "."); 20 s = regex_replace(s, regex(R"( \?)"), "?"); 21 s = regex_replace(s, regex(R"( ')"), "'"); 22 for (auto &c : s) 23 { 24 if(c != 'I') c = tolower(c); 25 } 26 s = regex_replace(s, regex(R"(\bcan you\b)"), "_I can"); 27 s = regex_replace(s, regex(R"(\bcould you\b)"), "_I could"); 28 s = regex_replace(s, regex(R"(\bI\b)"), "you"); 29 s = regex_replace(s, regex(R"(\bme\b)"), "you"); 30 s = regex_replace(s, regex(R"(\?)"), "!"); 31 s = regex_replace(s, regex(R"(\b_I\b)"), "I"); 32 cout << "AI: " << s << endl; 33 } 34 }
估值一亿的AI核心代码,这一题也是以前做过,没做出来,当时觉得很多条件要判断先后顺序什么的很复杂。
这次写的时候学了c++的正则写法还有模式匹配,写起来代码简短很多,也变得非常简单。
std::regex是C++用来表示「正则表达式」(regular expression)的库,于C++11加入,它是class std::basic_regex<>针对char类型的一个特化,还有一个针对wchar_t类型的特化为std::wregex。
符号 | 意义 |
---|---|
^ | 匹配行的开头 |
$ | 匹配行的结尾 |
. | 匹配任意单个字符 |
[…] | 匹配[]中的任意一个字符 |
(…) | 设定分组 |
\ | 转义字符 |
\d | 匹配数字[0-9] |
\D | \d 取反 |
\w | 匹配字母[a-z],数字,下划线 |
\W | \w 取反 |
\s | 匹配空格 |
\S | \s 取反 |
+ | 前面的元素重复1次或多次 |
* | 前面的元素重复任意次 |
? | 前面的元素重复0次或1次 |
{n} | 前面的元素重复n次 |
{n,} | 前面的元素重复至少n次 |
{n,m} | 前面的元素重复至少n次,至多m次 |
| | 逻辑或 |