5

我搜索,找不到任何东西。为了不再浪费我的时间在答案对其他人来说是显而易见的机会上,我在这里问。到目前为止唯一有用的站点是这个站点:http: //softwareramblings.com/2008/07/regular-expressions-in-c.html,但示例过于简单。我正在使用 Visual Studio 2010。

#include <regex>

[...]

string seq = "Some words. And... some punctuation.";
regex rgx("\w");

smatch result;
regex_search(seq, result, rgx);

for(size_t i=0; i<result.size(); ++i){
    cout << result[i] << endl;
}

预期输出为:

一些
单词

一些
标点符号

谢谢。

4

2 回答 2

5

这里有几件事。

首先,您的正则表达式字符串需要\转义。毕竟,它仍然是一个 C++ 字符串。

regex rgx("\\w");

此外,正则表达式\w只匹配一个“单词字符”。如果要匹配整个单词,则需要使用:

regex rgx("\\w+");

最后,为了遍历所有可能的匹配项,您需要使用迭代器。这是一个完整的工作示例:

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string seq = "Some words. And... some punctuation.";
    regex rgx("\\w+");

    for( sregex_iterator it(seq.begin(), seq.end(), rgx), it_end; it != it_end; ++it )
        cout << (*it)[0] << "\n";
}
于 2011-01-28T06:45:45.163 回答
1

尝试这个:

string seq = "Some words. And... some punctuation.";
regex rgx("(\\w+)");

regex_iterator<string::iterator> it(seq.begin(), seq.end(), rgx);
regex_iterator<string::iterator> end;

for (; it != end; ++it)
{
    cout << it->str() << endl;
}
于 2011-01-28T06:38:12.550 回答