2016-06-07 72 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見編輯 –