17.19 逻辑运算 || 为短路求值,调用到m[4].str()说明左侧的m[4].mached == 0不成立,直接可以判断m[4]已经匹配。
17.20
#include <iostream>
#include <string>
#include <regex>
using namespace std;
bool valid(const smatch &m)
{
if (m[1].matched)
return m[3].matched && (m[4].matched == 0 || m[4].str() == " ");
else
return !m[3].matched && m[4].str() == m[6].str();
}
int main()
{
string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
regex r(phone);
smatch m;
string s;
while (getline(cin, s)) {
for (sregex_iterator it(s.begin(), s.end(), r), end_it;
it != end_it; ++it)
if (valid(*it))
cout << "valid: " << it->str() << endl;
else
cout << "not valid: " << it->str() << endl;
}
return 0;
}
17.21
#include <iostream>
#include <regex>
#include <sstream>
#include <vector>
using namespace std;
struct PersonInfo {
string name;
vector<string> phones;
};
bool valid(const smatch &m)
{
if (m[1].matched)
return m[3].matched && (m[4].matched == 0 || m[4].str() == " ");
else
return !m[3].matched && m[4].str() == m[6].str();
}
int main()
{
string line, word;
vector<PersonInfo> people;
string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
regex r(phone);
while (getline(cin, line)) {
PersonInfo info;
istringstream record(line);
record >> info.name;
while (record >> word) {
for (sregex_iterator it(word.begin(), word.end(), r), end_it; it != end_it; ++it) {
if (!valid(*it))
cout << "invalid: " << it->str() << endl;
else
info.phones.push_back(word);
}
}
people.push_back(info);
}
for (auto &entry : people) {
cout << entry.name << ": ";
for (auto &item : entry.phones)
cout << item << " ";
cout << endl;
}
return 0;
}
17.22 修改正则表达式为:
string phone = "(\\()?(\\d{3})(\\))?([-.]|(\\s)*)?(\\d{3})([-.]|(\\s)*)?(\\d{4})";
17.23
string pattern = "(\\d{5})([-])?(\\d{4})?";
regex code(pattern);
517




被折叠的 条评论
为什么被折叠?



