最近学习了一下C++11引入的正则表达式用法,对于处理字符串问题带来很大方便。下面基于几个简单应用介绍一下用法:
(1) 判断字符串是否匹配某一模式,例如,判断输入字符串是否符合“5-15位数字,并且首位不能是0”这一模式。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
getline(cin, str);
//R"(字符串)" 是c++11引入的新特性,字符串中的\将不再被解释为转义字符,因此如果需要\d表示[0-9],可以直接使用'\d',降低阅读难度。
regex pattern(R"([1-9]\d{4,14})");
//如果不使用R"(字符串)"的用法,那么需要注意转义字符需要\\,如下
//regex pattern("[1-9]\\d{4,14}");
cout << (regex_match(str, pattern) ? "yes" : "no") << endl;
return 0;
}
这里使用的是regex_match函数,它将字符串s与模式re进行完全匹配,如果完全匹配成功返回true,否则返回false。
bool regex_match(const string& s, const regex& re)
(2) 依照模式分割字符串,例如,将字符串按照空格分割成若干个子串。
其实C++并没有提供split函数,但是可以利用正则表达式找到符合模式的子串。因此可以将这一问题进行转化,也就是找到字符串中所有不含空格的子串,那么也就完成了分割的任务。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
getline(cin, str);
regex pattern(R"([^\s]+)");
for(sregex_token_iterator it(str.begin(), str.end(), pattern), e; it != e; it++) cout << *it << endl;
return 0;
}
其中sregex_token_iterator是对string类特化的regex_token_iterator类,复杂用法还在摸索中,但是对于类似于匹配指定模式的子串这一类问题,可以记住这样使用就行。
有的时候需要需要对单词边界进行限制,例如在字符串中找到所有长度为3的单词,需要在模式中加入'\b'定位符,意为单词边界:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "abcd efg hijk lmn";
regex pattern(R"(\b[a-z]{3}\b)");
for(sregex_token_iterator it(str.begin(), str.end(), pattern), e; it != e; it++) cout << *it << " ";
return 0;
}
(3)将字符串中连续的相同字符只保留一个。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "abbccc";
regex pattern(R"((\w)\1+)");
str = regex_replace(str, pattern, "$1");
cout << str << endl;
return