我正在尝试运行the docs中找到的regex_search
函数的示例代码。
他们示例中的代码如下:
// regex_search example
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("this subject has a submarine as a subsequence");
std::smatch m;
std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
std::cout << "Target sequence: " << s << std::endl;
std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
std::cout << "The following matches and submatches were found:" << std::endl;
while (std::regex_search (s,m,e)) {
for (auto x:m) std::cout << x << " ";
std::cout << std::endl;
s = m.suffix().str();
}
return 0;
}
当我尝试在我的计算机上运行此代码时(我使用的是Ubuntu 16.04并使用g ++编译器),我在IDE上收到m
参数的以下警告:
Parameter type mismatch: Class 'std::smatch' is not compatible with class 'std::match_results<const char *, std::allocator<std::sub_match<std::basic_string<char, std::char_traits<char>, std::allocator<char>>::const_iterator>>>'
另一个s
参数:Parameter type mismatch: Types 'const char *' and 'std::string' are not compatible
。
当我尝试编译代码时,我得到了:
./src/launcher.cpp: In function ‘int main()’:
./src/launcher.cpp:18:3: error: ‘smatch’ was not declared in this scope
smatch m;
^
./src/launcher.cpp:18:3: note: suggested alternatives:
In file included from /usr/include/c++/5/regex:61:0,
from ./src/launcher.cpp:3:
/usr/include/c++/5/bits/regex.h:1900:50: note: ‘std::__cxx11::smatch’
typedef match_results<string::const_iterator> smatch;
^
/usr/include/c++/5/bits/regex.h:1900:50: note: ‘std::__cxx11::smatch’
./src/launcher.cpp:19:3: error: ‘regex’ was not declared in this scope
regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"
^
./src/launcher.cpp:19:3: note: suggested alternatives:
In file included from /usr/include/c++/5/regex:61:0,
from ./src/launcher.cpp:3:
/usr/include/c++/5/bits/regex.h:786:32: note: ‘std::__cxx11::regex’
typedef basic_regex<char> regex;
^
/usr/include/c++/5/bits/regex.h:786:32: note: ‘std::__cxx11::regex’
./src/launcher.cpp:25:26: error: ‘m’ was not declared in this scope
while (regex_search (s,m,e)) {
^
./src/launcher.cpp:25:28: error: ‘e’ was not declared in this scope
while (regex_search (s,m,e)) {
^
./src/launcher.cpp:26:17: error: unable to deduce ‘auto&&’ from ‘m’
for (auto x:m) std::cout << x << " ";
^
Makefile:21: recipe for target 'launcher.o' failed
make: *** [launcher.o] Error 1
我使用s
函数将问题转换为c-string,解决了c_str()
参数的问题。不过,我无法使用m
参数解决问题。
我尝试将m
的类型更改为match_results
(这是其模板类),但错误仍然存在。我还尝试将m
的类型更改为我的IDE上警告所建议的类型,但问题仍然存在。
我理解问题是m
的类型不是函数期望的类型,但我不知道如何解决它。
有人对如何解决这个问题有任何建议吗?
我的主要目标是调整该代码以提取包含某个子字符串的特定字符串,因此如果有人对如何做到这一点有任何建议,我将非常感激。