前端之家收集整理的这篇文章主要介绍了
使用正则表达式模拟读写INI文件,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#include "stdio.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <regex>
using namespace std;
void Trim(char * str);
void lTrim(char * str);
void rTrim(char * str);
void test1()
{
char url[] = "dv://192.168.1.253:65001/1/1";
char protocol[10];
char ip[17];
int port;
int chn;
int type;
sscanf(url,"%[^://]%*c%*c%*c%[^:]%*c%d%*c%d%*c%d",&port,&chn,&type);
printf("%s,%s,%d,%d\n",type);
}
void test2()
{
char line[1000] = { 0 };
char val[1000] = { 0 };
char key[1000] = { 0 };
FILE *fp = fopen("1.txt","r");
if (NULL == fp)
{
printf("Failed to open 1.txt\n");
return ;
}
while (!feof(fp))
{
memset(line,0,sizeof(line));
fgets(line,sizeof(line) - 1,fp);
printf("%s",line);
Trim(line);
memset(key,sizeof(key));
sscanf(line,"%[^ \t\n\r\f=]",key);
printf(" key: [%s]\n",key);
memset(val,sizeof(val));
sscanf(line,"%*[^=]%*c%[^\n]",val);
Trim(val);
printf(" val: [%s]\n",val);
}
printf("\n");
fclose(fp);
}
template<class T1,class T2>
inline T1 parseTo(const T2 t)
{
static stringstream sstream;
T1 r;
sstream << t;
sstream >> r;
sstream.clear();
return r;
}
string trim(string& s)
{
if (s.empty()) return s;
for (int i = 0; i < s.size(); i++)
{
if (s[i] != ' ' && s[i] != '\t' &&s[i] != '\n' && s[i] != '\r' && s[i] != '\f')
{
s.erase(0,i);
break;
}
}
for (int i = s.size() - 1; i > -1; i--)
{
if (s[i] != ' ' && s[i] != '\t' &&s[i] != '\n' && s[i] != '\r' && s[i] != '\f')
{
s.erase(i + 1);
break;
}
}
return s;
}
void test3()
{
char val[1000] = { 0 };
char key[1000] = { 0 };
ifstream fin("1.txt");
string line;
if (fin)
{
while (getline(fin,line))
{
cout << line << endl;
regex reg("^([\\s]*)([\\w\\-\\_]+)([\\s=]+).*$");
string key = regex_replace(line,reg,"$2");
cout << " key: {" << key << "}" << endl;
reg = regex("^([\\s]*)([\\w\\-\\_]+)([\\s=]+)(.*)([\\s]*)$");
string val = trim(regex_replace(line,"$4"));
cout << " val: {" << val << "}" << endl;
}
}
else
{
cout << "no such file" << endl;
}
}
void main()
{
test2();
test3();
}
void lTrim(char * str)
{
int i,len;
len = strlen(str);
for (i = 0; i<len; i++)
{
if (str[i] != ' ' && str[i] != '\t' && str[i] != '\n' && str[i] != '\r' && str[i] != '\f') break;
}
memmove(str,str + i,len - i + 1);
return;
}
void rTrim(char * str)
{
int i,len;
len = strlen(str);
for (i = len - 1; i >= 0; i--)
{
if ((str[i] != ' ') && (str[i] != 0x0a) && (str[i] != 0x0d) && (str[i] != '\t') && (str[i] != '\f')) break;
}
str[i + 1] = 0;
return;
}
void Trim(char * str)
{
int i,len;
len = strlen(str);
for (i = 0; i<len; i++)
{
if (str[i] != ' ' && str[i] != '\t' && str[i] != '\n' && str[i] != '\r' && str[i] != '\f') break;
}
memmove(str,len - i + 1);
len = strlen(str);
for (i = len - 1; i >= 0; i--)
{
if (str[i] != ' ' && str[i] != '\t' && str[i] != '\n' && str[i] != '\r' && str[i] != '\f') break;
}
str[i + 1] = 0;
return;
}