c++ - 使用 C++ STL 库查找变量模式

标签 c++ string algorithm stl

我有一个文件,我必须在其中寻找模式。

模式是这样的:

"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/

相关文章:

c++ - C++ 中的二叉树

java - 具有 3 个条件的字符串格式 : is it possible?

algorithm - 如何根据项目的重量将项目列表分成相等的分区?

c# - O(n^2) 与 O(n) 中的算法

C++ 变量类型限制

c++ - 从 C/C++ 在 Trac 中自动添加票证的最简单方法

c++:我在我的数组中得到了一个奇怪的值

java - Oracle 是否有可能改变 Java 计算 java.lang.String 哈希码的方式?

c - C 中的树遍历和串联崩溃

algorithm - 如何使用替换法解决以下递归问题?