我有一个文件,我必须在其中寻找模式。
模式是这样的:
"ABCD"
A、B、C、D 是变量,可以是 0-9 和 A-F,除此之外别无其他。
此文件中的几个示例字符串是:
at+creg=2
OK
at+creg?
+CREG: 2,1,"03EB","3AC7"
+CREG: 2,1,"03FC","9AC9"
我的模式匹配代码应该输出:
03EB, 3AC7, 03FC, 9AC9
我想使用 STL 库中的函数来执行此操作。
如果我们有两个字符串,比如:
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
然后我们可以使用
str.find(str2);
寻找图案针。
但在我的例子中,我没有固定的字符串,因为上面的 A、B、C、D 是可变的。所以请帮助我了解如何在这里进行。
最佳答案
您似乎在搜索十六进制数字。如果字母大小写不重要,那么您可以应用标准 C 函数 std::isxdigit
在 header 中声明 <cctype>
.通常 C 标准函数放在全局命名空间中。因此,您可以使用::isxdigit 来区别于具有两个参数的同名 C++ 函数。否则,您可以将函数包装在 std::function 中或将函数转换为所需的类型。
这是一个演示程序。而不是 std::find_if
我使用的算法 std::copy_if
算法仅用于演示目的。
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <cctype>
#include <iterator>
int main()
{
std::istringstream is( " ABC 123AA43 Jh12 76-12 fedcba1" );
std::copy_if ( std::istream_iterator<std::string>( is ),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>( std::cout, "\n" ),
[]( const std::string &s )
{
return std::all_of( std::begin( s ), std::end( s ), ::isxdigit );
} );
}
输出是
ABC
123AA43
fedcba1
关于c++ - 使用 C++ STL 库查找变量模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33934232/