C++ | 使用正则表达式匹配特定形式的字符串
在 C++ 中,可以使用 <regex> 头文件提供的正则表达式库来对特定形式的字符串进行匹配操作。
常用的正则表达式模式语法
-  普通字符: - 普通字符会按照其字面意义进行匹配,例如 a会匹配字符a。
 
- 普通字符会按照其字面意义进行匹配,例如 
-  转义字符: - \:用于转义特殊字符,例如- \\匹配- \。
- .:匹配除换行符外的任意字符。
 
-  字符类: - [abc]:匹配字符- a,- b, 或- c中的任意一个。
- [a-z]:匹配- a到- z范围内的任意字符。
- [^abc]:匹配除- a,- b, 和- c之外的任意字符。
 
-  重复次数: - *:匹配前面的子表达式零次或多次。
- +:匹配前面的子表达式一次或多次。
- ?:匹配前面的子表达式零次或一次。
- {n}:匹配前面的子表达式恰好- n次。
- {n,}:匹配前面的子表达式至少- n次。
- {n,m}:匹配前面的子表达式至少- n次但不超过- m次。
 
-  定位符: - ^:匹配输入字符串的开始。
- $:匹配输入字符串的结尾。
- \b:匹配单词边界。
 
-  捕获组: - (pattern):捕获匹配的子表达式。
 
-  特殊字符: - \d:匹配任意数字字符。
- \w:匹配任意字母、数字或下划线字符。
- \s:匹配任意空白字符。
 
使用正则表达式匹配字符串用法示例
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "(1,2),(2,3),(4,5)";// 定义正则表达式模式std::regex pattern("\\((\\d+),(\\d+)\\)");// 迭代器用于遍历匹配结果std::sregex_iterator it(input.begin(), input.end(), pattern);std::sregex_iterator end;// 遍历匹配结果并输出while (it != end) {std::smatch match = *it;std::cout << "Matched: " << match.str() << std::endl;std::cout << "Group 1: " << match[1].str() << std::endl; // 第一个括号内的数字std::cout << "Group 2: " << match[2].str() << std::endl; // 第二个括号内的数字++it;}return 0;
}
示例输出:
Matched: (1,2)
Group 1: 1
Group 2: 2
Matched: (2,3)
Group 1: 2
Group 2: 3
Matched: (4,5)
Group 1: 4
Group 2: 5