std::regex 的几种匹配方式
时间: 2023-11-10 13:39:02 浏览: 37
std::regex 包含三种匹配方式:全串匹配、局部匹配和迭代器匹配。其中,全串匹配是默认的匹配方式,使用 std::regex_match() 函数;局部匹配使用 std::regex_search() 函数;迭代器匹配使用 std::regex_iterator 和 std::sregex_iterator 类。
相关问题
std::regex_search只能匹配一个模式串吗
不是的,std::regex_search可以匹配多个模式串。它的第三个参数是一个std::match_results对象的引用,可以存储所有匹配到的结果,包括每个匹配的子串、每个子串的位置等信息。你可以通过循环遍历这个std::match_results对象,来获取所有匹配到的结果。以下是一个示例代码:
```cpp
#include <iostream>
#include <regex>
int main()
{
std::string s = "Hello, world! This is a test string.";
std::regex pattern("\\w+");
std::smatch matches;
while (std::regex_search(s, matches, pattern)) {
for (auto match : matches) {
std::cout << match.str() << " ";
}
std::cout << std::endl;
s = matches.suffix().str();
}
return 0;
}
```
输出结果:
```
Hello world
This is a test string
```
可以看到,通过循环遍历std::match_results对象,我们获取了所有匹配到的单词。
std::regex
std::regex是C++标准库中用于正则表达式匹配和替换的类。它提供了一种强大的方式来处理字符串模式匹配和操作。
使用std::regex,你可以根据特定的模式来搜索、匹配和替换字符串。它支持多种正则表达式语法,并具有灵活的功能。
下面是一个简单的示例,演示了如何使用std::regex进行匹配和替换:
```cpp
#include <iostream>
#include <regex>
int main() {
std::string text = "Hello, world!";
std::regex pattern("world");
if (std::regex_search(text, pattern)) {
std::cout << "Pattern found in the text." << std::endl;
}
std::string replaced_text = std::regex_replace(text, pattern, "C++");
std::cout << "Replaced text: " << replaced_text << std::endl;
return 0;
}
```
输出:
```
Pattern found in the text.
Replaced text: Hello, C++!
```