C++11新特性_标准库_正则表达式库
C++11 引入了标准正则表达式库 <regex>
,它提供了强大且灵活的文本匹配和替换功能。下面为你详细介绍该库的相关内容,包括主要组件、使用方法、示例代码等。
主要组件
std::regex
:用于表示一个正则表达式对象,可通过构造函数将字符串形式的正则表达式转换为内部表示形式。std::smatch
:用于存储字符串匹配的结果,包含了匹配的子字符串及其位置等信息。std::regex_match
:用于判断整个输入字符串是否与正则表达式匹配。std::regex_search
:用于在输入字符串中查找与正则表达式匹配的子字符串。std::regex_replace
:用于将输入字符串中与正则表达式匹配的部分替换为指定的字符串。
使用方法
1. 基本匹配
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "hello world";std::regex pattern("hello");if (std::regex_search(input, pattern)) {std::cout << "找到匹配项" << std::endl;} else {std::cout << "未找到匹配项" << std::endl;}return 0;
}
在上述代码中,首先定义了一个输入字符串 input
和一个正则表达式对象 pattern
,然后使用 std::regex_search
函数在 input
中查找与 pattern
匹配的子字符串。
2. 完整匹配
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "hello";std::regex pattern("hello");if (std::regex_match(input, pattern)) {std::cout << "完全匹配" << std::endl;} else {std::cout << "不完全匹配" << std::endl;}return 0;
}
这里使用 std::regex_match
函数判断 input
是否与 pattern
完全匹配。
3. 捕获组
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "John Doe, 25";std::regex pattern("(\\w+) (\\w+), (\\d+)");std::smatch matches;if (std::regex_search(input, matches, pattern)) {std::cout << "姓名: " << matches[1] << " " << matches[2] << std::endl;std::cout << "年龄: " << matches[3] << std::endl;}return 0;
}
通过在正则表达式中使用括号 ()
定义捕获组,std::smatch
对象 matches
可以存储每个捕获组匹配的结果,通过索引访问这些结果。
4. 替换操作
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "Hello, World!";std::regex pattern("World");std::string replacement = "C++";std::string result = std::regex_replace(input, pattern, replacement);std::cout << "替换后的字符串: " << result << std::endl;return 0;
}
使用 std::regex_replace
函数将 input
中与 pattern
匹配的部分替换为 replacement
。
注意事项
- 正则表达式语法:C++ 的正则表达式库支持多种正则表达式语法,如 ECMAScript、basic、extended 等,默认使用 ECMAScript 语法。
- 性能问题:正则表达式匹配可能会带来一定的性能开销,特别是对于复杂的正则表达式和长字符串,使用时需要注意性能优化。
- 异常处理:在构造
std::regex
对象时,如果正则表达式语法错误,会抛std::regex_error
异常,需要进行适当的异常处理。