在c++中使用正则表达式时出现错误
getting error using regex in C++
给定输入有4行,我应该找出有多少行有word hacker
4
I love #hacker
I just scored 27 points in the Picking Cards challenge on #Hacker
I just signed up for summer cup @hacker
interesting talk by hari, co-founder of hacker
答案是4,但我得到它是0。
int main() {
int count = 0,t;
cin >> t;
string s;
bool ans;
while(t--){
cin >> s;
smatch sm;
regex rgx("hacker",regex_constants::icase);
ans = regex_match(s,sm,rgx);
if(ans){
count += 1;
}
}
cout << ans << endl;
return 0;
}
-
你的while循环只运行
t
次,每次它只读取一个单词。所以你的程序现在将只读取前三个单词,然后终止。 -
你只匹配了整个单词。在
#hacker
和@hacker
的情况下,没有匹配 -
我相信你想在最后计算
count
而不是ans
。
您应该使用std::getline
来读取字符串(包含空格)。此外,您应该使用std::regex_search
来搜索'部分'匹配(std::regex_match
只会在regex匹配整个字符串时匹配)。
你的代码稍微修改了一下:
#include <regex>
#include <iostream>
#include <string>
int main() {
int count = 0,t;
std::cin >> t;
std::string s;
std::smatch sm;
std::regex rgx("hacker", std::regex_constants::icase);
for(int i = 0; i < t; ++i)
{
std::getline(std::cin, s);
while(std::regex_search(s, sm, rgx))
{
++count;
s = sm.suffix().str();
}
}
std::cout << count << std::endl;
return 0;
}
如果您按照以下方式更改正则表达式,您将得到预期的结果:
regex rgx("(.*)hacker(.*)",regex_constants::icase);
它比较的是整个字符串的匹配
否则你必须使用std::regex_search
来代替std::regex_match
ans = regex_search(s,sm,rgx);
演示:http://coliru.stacked-crooked.com/a/f28c2e4b315f6f0a
看起来第一个单词应该是输入的行数。但是,尽管看起来您想处理四行输入,但输入显示
问题已被编辑。
3
.
你读的不是行,而是字符串,可以翻译成单独的单词。使用getline()
获取一行输入
while(t--){
std::getline(std::cin, s);
//...
正则表达式格式错误。只有当一行只包含单词"hacker"时,它才会匹配。你想看看hacker是否在这行,所以让你的模式匹配"hacker"周围的其余部分。
regex rgx(".*hacker.*",regex_constants::icase);
当你发出你的答案时,似乎你想发出count
,而不是ans
。
相关文章:
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- std::正则表达式捕获组语法错误
- 带有正则表达式的 c++ 中的错误
- 为什么这个正则表达式在 STL 世界中是错误的?
- C++抛出错误"Invalid special open parenthesis."中的正则表达式
- 正则表达式分段错误
- 使用boost正则表达式时出现shared_ptr错误
- 正则表达式中带有卷轴大括号的正则表达式错误
- 提升正则表达式错误:未初始化的提升::match_results
- C++ 正则表达式错误(未处理的异常)
- 提升正则表达式中的链接器错误
- Ubuntu 上的正则表达式错误
- C++正则表达式错误
- Mingw32-w64 GCC 4.9.2 正则表达式错误,或者我不知道C++
- 函数正则表达式C++在 linux(CentOS) 中遇到错误,但在 OSX 中
- 在 C++14 模式下为 libstdc++ 编译 clang 正则表达式程序会导致错误
- boost的正则表达式错误
- 在c++中使用正则表达式时出现错误
- 提升::正则表达式在长表达式不匹配时抛出错误