【问题标题】:Regex behaving differently within C++正则表达式在 C++ 中的行为不同
【发布时间】:2018-04-24 13:31:33
【问题描述】:

我编写了一个正则表达式,用于解析日志字符串的各种元素,格式如下:

0|详细|一般|日志系统已初始化

0|详细|主题|正在启动线程...

0|详细|主题|等待线程完成...

表达式:

regex rg(R"(\s*(\d+)\|\s*([a-zA-Z]+)\|\s*([a-zA-Z]+)\|\s*([a-zA-Z\s]+))");

在在线测试人员(例如https://regexr.com/)中,它按预期工作。

但是,当我在我的 C++ 程序中使用它时,它会将第一个日志字符串拆分如下:

0

|详细|一般|

记录

系统

我尝试过使用各种 std::regex_constant 参数(例如扩展、基本、ECMAScript),但没有成功。

任何想法为什么会发生这种情况/我做错了什么?我是正则表达式的新手

【问题讨论】:

  • 你能告诉我们哪个编译器吗?
  • MinGW g++ 版本 5.1.0。刚刚尝试更新到 v. 6.3.0 并且可执行文件在启动时崩溃了,但这是一个不同的问题!
  • 这肯定是与旧版本相关的库问题。在 gcc online 上,它按预期工作:ideone.com/ifRW8V 或者,您可以尝试使用正则表达式库的 boost 版本。
  • 也许它不能识别类似 Perl 的速记字符类?尝试将\s 替换为[[:space:]](如果是独立的)或[:space:](在字符类中),将\d 替换为[[:digit:]][[:space:]]*([[:digit:]]+)\|[[:space:]]*([a-zA-Z]+)\|[[:space:]]*([a-zA-Z]+)\|[[:space:]]*([a-zA-Z[:space:]]+))。
  • @MaxFuller 1) 尝试让较新的 MingW 版本工作 2) 如果较新的版本不能解决问题,作为一种解决方法,获取 boost 库并使用 boost::regex 而不是 std::regex 3) 考虑迁移到另一个更可靠的 Windows 编译器(例如 MSVC 或 clang)

标签: c++ regex mingw


【解决方案1】:

晚了一天,还缺一美元 (:-( ... (:-),但是:

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

using namespace std;

int main(int argc, char *argv[]) {
    string str = "0|Verbose|General| Logging system initialised";
    regex rg(R"(\s*(\d+)\|\s*([a-zA-Z]+)\|\s*([a-zA-Z]+)\|\s*([a-zA-Z\s]+))");
    smatch match;

    if (regex_match(str, match, rg)) {
        cout << "is a match" << endl;
        int nSubs = match.size();
        for (int i = 1; i < nSubs; i++) {
            cout << i << ": " << match[i] << endl;
        }
    } else {
        cout << "not a match" << endl;
    }
}

输出:

[test]: ./re1
is a match
1: 0
2: Verbose
3: General
4: Logging system initialised
[test]: 

使用:

[test]: g++ --version
g++ (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

[test]: 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多