


Detailed explanation of the steps for regex simulation to read INI files
这次给大家带来正则模拟读取INI文件的步奏详解,使用正则模拟读取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); // 测试sscanf 和 正则表达式 // sscanf提供的这个扩展功能其实并不能真正称为正则表达式,因为他的书写还是离不开% // []表示字符范围,{}表示重复次数,^表示取非,*表示跳过。所以上面这个url的解析可以写成下面这个样子: // //char url[] = "dv://192.168.1.253:65001/1/1" // //sscanf(url, "%[^://]%*c%*c%*c%[^:]%*c%d%*c%d%*c%d", protocol, ip, port, chn, type); // //解释一下 //先取得一个最长的字符串,但不包括字串 ://,于是protocol="dv\0"; //然后跳过三个字符,(%*c)其实就是跳过 :// // 接着取一个字符串不包括字符串 : ,于是ip = 192.168.1.253,这里简化处理了,IP就当个字符串来弄,而且不做检查 // 然后跳过冒号取端口到port,再跳过 / 取通道号到chn,再跳过 / 取码流类型到type。 // c语言实现上例 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", protocol, ip, &port, &chn, &type); printf("%s, %s, %d, %d, %d\n", protocol, ip, port, chn, type); } // 读取ini里某行字符串, 得到: hello world! // 正常串1: -claim="hello world!" // 正常串2: claim = "hello world!" // 正常串3: claim = " hello world!" // 正常串4: claim_ = hello world! // 干扰串1: cl-aim = \"hello world!" // 干扰串2: clai3m = "hello world!\" // 干扰串3: cla_im = \\"hello world!\" // 干扰串4: claim ='"hello world!\" // 干扰串5: claim= @"\nhello world!" // 干扰串6: claim=L"hello world!" // 未处理1: claim[1] = 1 // 未处理1: claim[2] = 1 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); // 包含了每行的\n printf("%s", line); Trim(line); // 提取等号之前的内容 memset(key, 0, sizeof(key)); // sscanf使用的format不是正则表达式,不能用 \\s 表示各种空白符,即空格或\t,\n,\r,\f sscanf(line, "%[^ \t\n\r\f=]", key); //sscanf(line, "%*[^a-zA-Z0-9_-]%[^ \t\n\r\f=]", key); printf(" key: [%s]\n", key); // 提取等号之后的内容 memset(val, 0, sizeof(val)); sscanf(line, "%*[^=]%*c%[^\n]", val); // 不包含了每行的换行符 Trim(val); printf(" val: [%s]\n", val); // 去除两边双引号 // ... // 插入map // map[key]=value; // string 转 其它类型 // atoi, atol, atof } printf("\n"); fclose(fp); } // 上例的C++实现 template<class T1, class T2> inline T1 parseTo(const T2 t) { static stringstream sstream; T1 r; sstream << t; sstream >> r; sstream.clear(); return r; } void test3() { char val[1000] = { 0 }; char key[1000] = { 0 }; ifstream fin("1.txt"); string line; if (fin) { while (getline(fin, line)) // line中不包括每行的换行符 { cout << line << endl; /// 提取等号之前的内容 // 第1组()表示任意个空格字符,第2组()表示单词(可带_或-), // 第3组()表示1个以上的空格字符(或=),最后以任意字符串结尾 regex reg("^([\\s]*)([\\w\\-\\_]+)([\\s=]+).*$"); // 取第2组代替原串 string key = regex_replace(line, reg, "$2"); cout << " key: {" << key << "}" << endl; /// 提取等号之后的内容 // 第1组()表示任意个空格字符,第2组()表示单词(可带_或-), // 第3组()表示1个以上的空格字符(或=),第4组()表示任意个字符, // 第5组()表示以任意个空格字符(或回车换行符)结尾。 reg = regex("^([\\s]*)([\\w\\-\\_]+)([\\s=]+)(.*)([\\s\\r\\n]*)$"); // 取第4组代替原串 string val = regex_replace(line, reg, "$4"); cout << " val: {" << val << "}" << endl; // 去除两边双引号 // ... // 插入map // map[key]=value; // string 转 其它类型 // int i = parseTo<int>("123"); // float f = parseTo<float>("1.23"); // string str = parseTo<string>(123); } } else // 没有该文件 { cout << "no such file" << endl; } } void main() { //test1(); 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, str + i, 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; } /* void Trim(char * str) { lTrim(str); rTrim(str); } */
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the steps for regex simulation to read INI files. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus
