2014-02-13 56 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