2016-06-07 69 views
1

我想用C++ 11的正则表达式来完成一个非常简单的过滤任务,但是我无法让它像我想要的那样工作。于是我开始写一个单独的演示程序。std :: regex与g ++失败?

事情是,最简单的事情失败悲惨。例如:

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

int main() 
{ 
    std::vector<std::string> inputs; 
    inputs.push_back("1"); 
    inputs.push_back("123"); 
    inputs.push_back("a"); 
    inputs.push_back("apple"); 
    inputs.push_back(":apple3.worm"); 

    std::string pattern("[0-9]"); 
    std::regex r(pattern, std::regex_constants::grep); 

    for(auto const &s: inputs) 
    { 
    bool ok = std::regex_match(s, r); 
    std::cout << (ok?"POS":"NEG") << ": " << s << std::endl; 
    } 
    return 0; 
} 

编译时没有与g++ -Wextra -pedantic -std=c++11 -O3 rfail.cpp -o rfail警告。输出:当我[[:digit:]]取代[0-9]

POS: 1 
NEG: 123 
POS: a 
NEG: apple 
NEG: :apple3.worm 

同样happend。发生什么事?我做错了什么?

更新:

$ g++ -v 
Using built-in specs. 
COLLECT_GCC=g++ 
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.8/lto-wrapper 
Target: x86_64-linux-gnu 
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.8.4-2ubuntu1~14.04.3' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libmudflap --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu 
Thread model: posix 
gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) 
+0

你应该给我们更多关于你的'g ++'的信息 –

回答

1

如果carefuly阅读regex_match文档,你会发现:

整个靶序列必须的正则表达式这个函数返回true匹配 (即,在比赛之前或之后没有任何额外的字符)。对于匹配只是序列的一部分时返回true的函数,请参阅regex_search。

因此,如果您要检查,如果你的字符串中包含至少1个号码,你的正则表达式改为.*[0-9].*


请注意,我不能重现你的输出,我的是:

POS: 1 
NEG: 123 
NEG: a // <- here's the diff 
NEG: apple 
NEG: :apple3.worm 

(与Apple LLVM version 7.3.0 (clang-703.0.29)编译)


鉴于您的gcc版本,它似乎正在运行<regex>的高度实验性实现,该实施已包含在gcc 4.9more information about the bug here中。

如果考虑在代码中使用正则表达式,则应该考虑更新。

+0

为什么'[0-9]'匹配'a'? – Zereges

+0

我得到你所说的完整匹配。我的问题是输出中的第三行。我会用g ++版本更新我的文章。 – Notinlist

+0

@Notinlist见编辑 –