2014-02-13 125 views
1

我試圖按照這裏的例子:boost正則表達式不匹配?

http://www.boost.org/doc/libs/1_31_0/libs/regex/doc/syntax.html

我想匹配這種形式的行:

[ foo77 ] 

應該是足夠簡單,我試過的代碼片段是這樣的:

boost::regex rx("^\[ (.+) \]"); 

boost::cmatch what; 
if (boost::regex_match(line.c_str(), what, rx)) std::cout << line << std::endl; 

但我不符合這些線。我嘗試了以下變體表達式:

"^\[[:space:]+(.+)[:space:]+\]$" //matches nothing 
"^\[[:space:]+(.+)[:space:]+\]$" //matches other lines but not the ones I want. 

我做錯了什麼?

+0

快速猜測:您可能必須轉義'\'。在你的情況:boost :: regex rx(「^ \\\ [(。+)\\\]」); – tgmath

回答

1

更改boost::regex rx("^\[ (.+) \]");boost::regex rx("^\\[ (.+) \\]");,它會正常工作,編譯器應警告有關無法識別的字符轉義序列。

0

您需要在正則表達式中跳過\,否則編譯器會將"\["視爲(無效)轉義序列。

boost::regex rx("^\\[ (.+) \\]"); 

更好的解決方案是使用raw string literals

boost::regex rx(R"(^\[ (.+) \])"); 
+0

原始字符串文字僅在C++ 11中可用。如果他有C++ 11,他會使用'std :: regex'而不是Boost(推測至少)。 –

+0

@James除非他使用gcc,否則'std :: regex'在4.9之前的版本中並不適用。 – Praetorian