下面來(lái)介紹和regex_match()很像的regex_search()的使用實(shí)例,regex_match()要求正則表達(dá)式必須與模式串完全匹配,regex_search()只要求存在匹配項(xiàng)就可以。
#include <regex>
#include <iostream>
#include <string>
int main()
{
const std::tr1::regex pattern("(\\w+day)");
// the source text
std::string weekend = "Saturday and Sunday";
std::smatch result;
bool match = std::regex_search(weekend, result, pattern);
if(match)
{
for(size_t i = 1; i < result.size(); ++i)
{
std::cout << result[i] << std::endl;
}
}
std::cout<<std::endl;
return 0;
}
運(yùn)行結(jié)果:
上面這個(gè)例子只能返回第一個(gè)匹配的項(xiàng),如果要返回所有匹配的子序列,可以使用下面的方式:
#include <regex>
#include <iostream>
#include <string>
int main()
{
// regular expression
const std::regex pattern("\\w+day");
// the source text
std::string weekend = "Saturday and Sunday, but some Fridays also.";
const std::sregex_token_iterator end; //需要注意一下這里
for (std::sregex_token_iterator i(weekend.begin(),weekend.end(), pattern); i != end ; ++i)
{
std::cout << *i << std::endl;
}
std::cout<<std::endl;
return 0;
}
運(yùn)行結(jié)果:
下面的例子將元音字母打頭的單詞前面的a替換為an:
#include <regex>
#include <iostream>
#include <string>
int main()
{
// text to transform
std::string text = "This is a element and this a unique ID.";
// regular expression with two capture groups
const std::regex pattern("(\\ba (a|e|i|u|o))+");
// the pattern for the transformation, using the second
// capture group
std::string replace = "an $2";
std::string newtext = std::regex_replace(text, pattern, replace);
std::cout << newtext << std::endl;
std::cout << std::endl;
return 0;
}
運(yùn)行結(jié)果:
還是來(lái)說(shuō)明一下,這里主要使用了regex_replace(text, pattern, replace),意思是將text的內(nèi)容按照pattern進(jìn)行匹配,匹配成功的使用replace串進(jìn)行替換,并將替換后的結(jié)果作為函數(shù)值返回。需要注意的是std::string replace = "an $2"; 這里‘$2’表示模式串的第二個(gè)子表達(dá)式,
也就是以a,e,i,o,u開(kāi)頭的單詞。
聯(lián)系客服