您的位置:首页 > 其它

第十七章 17.3.1节练习

2014-10-07 20:04 155 查看
练习17.14

编写几个正则表达式,分别触发不同错误。运行你的程序,观察编译器对每个错误的输出。

解答:

这个就不一一列举出来了。如果正则表达式写错,在运行时程序会在编译表达式的时候直接崩溃。

练习17.15

编写程序,使用模式查找违反“i在e之前,除非在c之后”规则的单词。你的程序应该提示用户输入一个单词,然后掷出此单词是够符合要求。用一些违反和未违反规则的单词测试你的程序。

解答:

#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main(){
	string pattern("[^c]ei");
	pattern = "[[:alpha:]]+" + pattern + "[[:alpha:]]*";
	regex r(pattern);
	smatch results;

	string test_str;

	while (cout << "\nPlease enter a word for test:" << endl, cin >> test_str){
		if (regex_search(test_str, results, r))
			cout << "this word fit the requirements." << endl;
		else
			cout << "this word don't fit the requirements." << endl;
	}
}


练习17.16

如果前一题程序中的regex对象用“[^c]ei"进行初始化,将会发生什么?用词模式测试你的程序,检查你的答案是否正确。

解答:

#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main(){
	string pattern("[^c]ei");
	pattern = "[[:alpha:]]+" + pattern + "[[:alpha:]]*";
	//regex r(pattern);
	regex r("[^c]ei");
	smatch results;

	string test_str;

	while (cout << "\nPlease enter a word for test:" << endl, cin >> test_str){
		if (regex_search(test_str, results, r))
			cout << "this word fit the requirements." << endl;
		else
			cout << "this word don't fit the requirements." << endl;
	}
}
在VS2013中并没有什么影响。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: