C ++正则表达式示例输出与官方的有所不同

时间:2018-11-04 08:08:37

标签: c++ regex clang c++14 linuxmint

以下代码片段来自cppreference#regex

#include <iostream>
#include <iterator>
#include <string>
#include <regex>

int main()
{
    std::string s = "Some people, when confronted with a problem, think "
        "\"I know, I'll use regular expressions.\" "
        "Now they have two problems.";

    std::regex self_regex("REGULAR EXPRESSIONS",
            std::regex_constants::ECMAScript | std::regex_constants::icase);
    if (std::regex_search(s, self_regex)) {
        std::cout << "Text contains the phrase 'regular expressions'\n";
    }

    std::regex word_regex("(\\S+)");
    auto words_begin = 
        std::sregex_iterator(s.begin(), s.end(), word_regex);
    auto words_end = std::sregex_iterator();

    std::cout << "Found "
              << std::distance(words_begin, words_end)
              << " words\n";

    const int N = 6;
    std::cout << "Words longer than " << N << " characters:\n";
    for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
        std::smatch match = *i;
        std::string match_str = match.str();
        if (match_str.size() > N) {
            std::cout << "  " << match_str << '\n';
        }
    }

    std::regex long_word_regex("(\\w{7,})");
    std::string new_s = std::regex_replace(s, long_word_regex, "[$&]");
    std::cout << new_s << '\n';
}

它可以很好地编译,但是输出与我从中复制的示例页面不同:

Text contains the phrase 'regular expressions'
Found 0 words
Words longer than 6 characters:
Some [people,] when [confronted] with a [problem,] think "I know, I'll use [regular] [expressions."] Now they have two [problems.]

应该是:

Text contains the phrase 'regular expressions'
Found 19 words
Words longer than 6 characters:
  people,
  confronted
  problem,
  regular
  expressions."
  problems.
Some people, when [confronted] with a [problem], think 
"I know, I'll use [regular] [expressions]." Now they have two [problems].

我的笔记本电脑信息:

  

Linux 4.15.0-33-generic#36-Ubuntu SMP Wed Aug 15 16:00:05 UTC 2018 x86_64 x86_64 x86_64 GNU / Linux

我的编译器信息:

  

clang版本6.0.0-1ubuntu2(标签/ RELEASE_600 / final)   目标:x86_64-pc-linux-gnu   线程模型:posix

是什么导致差异?编译器版本?

我应该怎么做才能使其正常工作?

0 个答案:

没有答案