正则表达式编程实例
1.使用c++的正则表达式替换对应内容
std::string sKey = it->first;
std::string sPattern = "(<)(/)?(" + sKey + ")(>)";
std::regex rPattern(sPattern);
std::string sReplace = "$1$2" + it->second + "$4";
sMsg = std::regex_replace(sMsg, rPattern, sReplace);
sKey为要查找的关键词。sPattern为关键词加上正则格式后的字符串, "(<)(/)?(" + sKey + ")(>)",第一个()中表示有一个"<",第二个()后的?表示在<后是否存在?。整体意思为查"<heros1>", "</heros1>"这样的字符串。 sReplace为匹配串模式 "$1$2" + it->second + "$4" 表示第1,2,4个单元串不会参与到替换。
2.找出所有的坐标点
std::smatch rPotRet;
std::regex rPotPattern("[(]([0-9]+),([0-9]+)[)]");
const std::sregex_token_iterator end;
for (std::sregex_token_iterator itPot(sMsg.begin(), sMsg.end(), rPotPattern); itPot != end; ++itPot)
{
std::string sPot = *itPot;
if (std::regex_search(sPot, rPotRet, rPotPattern))
{
CPoint pot;
pot.x = atoi(rPotRet[1].str().c_str());
pot.y = atoi(rPotRet[2].str().c_str());
vecPot.push_back(pot);
}
}
"[(]([0-9]+),([0-9]+)[)]": [(]为必有一个(;[0-9]+表示有若干个0-9的数。整个意思就是查找 "(20,89)" ,“(1,22)”这样的字符串。
源代码
// regex1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <regex>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include "Windows.h"
#include "Windef.h"
#include "atltypes.h"
typedef std::map<std::string, std::string> MapColorType;
MapColorType GmapColor;
void mapColorInit()
{
GmapColor.insert(MapColorType::value_type("heros1", "12FFFGSEVF"));
GmapColor.insert(MapColorType::value_type("heros2", "22FDGRG7"));
GmapColor.insert(MapColorType::value_type("location", "24FDGRG7"));
}
std::string regexDeal(std::string sMsg, MapColorType mapColor, std::vector<CPoint>& vecPot)
{
std::string sRet;
for (MapColorType::iterator it = mapColor.begin(); it != mapColor.end(); it++)
{
std::string sKey = it->first;
std::string sPattern = "(<)(/)?(" + sKey + ")(>)";
std::regex rPattern(sPattern);
std::string sReplace = "$1$2" + it->second + "$4";
sMsg = std::regex_replace(sMsg, rPattern, sReplace);
if (sKey == "location")
{
std::smatch rPotRet;
std::regex rPotPattern("[(]([0-9]+),([0-9]+)[)]");
const std::sregex_token_iterator end;
for (std::sregex_token_iterator itPot(sMsg.begin(), sMsg.end(), rPotPattern); itPot != end; ++itPot)
{
std::string sPot = *itPot;
if (std::regex_search(sPot, rPotRet, rPotPattern))
{
CPoint pot;
pot.x = atoi(rPotRet[1].str().c_str());
pot.y = atoi(rPotRet[2].str().c_str());
vecPot.push_back(pot);
}
}
}
}
return sMsg;
}
int main()
{
mapColorInit();
std::vector<CPoint> vecPot;
std::string text = "<heros1>sixi</heros1><location>(11,11)</location><location>(22,22)</location>";
std::string sRet = regexDeal(text, GmapColor, vecPot);
std::cout <<"Input:" << text << std::endl;
std::cout << "Out:"<<sRet << std::endl;
for (std::vector<CPoint>::iterator it = vecPot.begin(); it != vecPot.end(); it++)
{
std::cout << it->x << std::endl;
std::cout << it->y << std::endl;
}
return 0;
}
运行效果