如何在C++11 std::regex中迭代所有std::string中的正则表达式匹配及其起始位置?

bluesky1年前 ⋅ 152 阅读

ChatGPT的回答仅作参考:

可以使用std::sregex_iterator来迭代所有匹配项。以下是一个示例代码:

```c++
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string str = "Hello, world! This is a test string.";
    std::regex pattern("\\w+"); // 匹配单词

    // 使用sregex_iterator迭代所有匹配项
    for (std::sregex_iterator it(str.begin(), str.end(), pattern), end; it != end; ++it) {
        std::smatch match = *it;
        std::cout << "Match: " << match.str() << " at position " << match.position() << std::endl;
    }

    return 0;
}
```

输出:

```
Match: Hello at position 0
Match: world at position 7
Match: This at position 14
Match: is at position 19
Match: a at position 22
Match: test at position 24
Match: string at position 29
```

在上面的代码中,我们使用std::sregex_iterator来迭代所有匹配项。它的构造函数接受三个参数:字符串的起始迭代器、字符串的结束迭代器和正则表达式。在迭代过程中,我们使用std::smatch来存储匹配结果,并使用smatch的position()方法来获取匹配项在字符串中的起始位置。

全部评论: 0

    相关推荐