1. 程式人生 > >Boost(五)——字串處理(二):正則表示式操作

Boost(五)——字串處理(二):正則表示式操作

正則表示式:

一些簡單的描述符:

. 匹配除換行符以外的任意字元

\w 匹配字母或數字或下劃線或漢字 等價於 '[^A-Za-z0-9_]'。

\s 匹配任意的空白符

\d 匹配數字

\b 匹配單詞的開始或結束

^ 匹配字串的開始

$ 匹配字串的結束

一、字串與正則表示式的比較

正則匹配: \\w+\\s\\w+ 形式(w+ 與w差不多 ,“+”意義:至少匹配一次)

std::string s = "hello world";
boost::regex expr("\\w+\\s\\w+");
boost::regex_match(s, expr); 

二、字串中搜索正則表示式

std::string s = "hello world";
boost::smatch what;
boost::regex expr("\\w+\\s\\w+");
boost::regex_search(s, what, expr); 

 儲存結果的類 boost::smatch(boost::match_results<string::const_iterator>)事實上是持有型別為 boost::sub_match 的元素的容器。

boost::regex_search()函式將正則搜尋結果寫入 v中

boost::match_results類內部過載了"[]"運算子,能用下標法讀取。

std::string s = "hello world";
boost::smatch what;
boost::match_results<string::const_iterator> v;
boost::regex expr("(\\w+)\\s(\\w+)");
if (boost::regex_search(s, v, expr))
{
	cout << v.size() << endl;
	cout << v[0] << endl;
	cout << v[1] << endl;
}

就算越界也沒事。

三、正則表示式替換字串

string s = "hello world";
boost::regex expr("(\\w+)\\s(\\w+)");
string fmt = "_";
boost::regex_replace(s, expr, fmt); //輸出結果是hello_world

互換位置:

string s = "hello world";
boost::regex expr("(\\w+)\\s(\\w+)");
string fmt = "\\2 \\1";
boost::regex_replace(s, expr, fmt); //輸出結果是world hello

 boost::regex_constants::format_literal 標誌作為第四引數傳遞給函式 boost::regex_replace() ,從而抑制了格式引數中對特殊字元的處理。

string s = "hello world";
boost::regex expr("(\\w+)\\s(\\w+)");
string fmt = "\\2 \\1";
boost::regex_replace(s, expr, fmt, boost::regex_constants::format_literal); //輸出結果是\2 \1

boost::algorithm::find_regex() 、 boost::algorithm::replace_regex() 、 boost::algorithm::erase_regex() 以及 boost::algorithm::split_regex() 等等與boost::regex_...形式類似

例如:

boost::algorithm::replace_regex(s, expr, fmt);//直接修改了s字串
cout << boost::algorithm::find_regex(s, expr) << endl;
boost::algorithm::erase_regex(s, expr);//直接修改了s字串
vector<string> v;
boost::algorithm::split_regex(v, s, expr);//用容器儲存分割結果