【问题标题】:How to use wildcard for strings (matching and replacing)?如何对字符串使用通配符(匹配和替换)?
【发布时间】:2011-11-12 16:32:07
【问题描述】:

我想搜索多个字母,包括 ? 替换为 C++ 中字符串中匹配的字母。

想像abcdefgh 这样的词。我想找到一种算法来搜索输入?c 以查找被? 替换的任何字母,并找到bc,但它还应该检查?e? 并找到def

你有什么想法吗?

【问题讨论】:

  • 听起来像是 正则表达式 的一个很好的例子,现在是<regex> 中标准库的一部分。

标签: c++ string wildcard match


【解决方案1】:

使用 boost::regex 怎么样?或 std::regex 如果您使用的是启用 c++11 的编译器。

【讨论】:

  • 实际上,我正在使用 xcode。有没有更好的方法使用字符串函数(substr 等)?
  • 全功能模式匹配并不容易实现,但如果使用 '?' 会容易得多是您唯一需要的。
【解决方案2】:

如果你只是想支持?,那很简单:当你在模式中遇到?时,只需向前跳过一个字节的输入(或者检查isalpha,如果你真的只想要匹配字母)。

编辑:假设更复杂的问题(从输入字符串的任何位置开始查找匹配项),您可以使用如下代码:

#include <string>

size_t match(std::string const &pat, std::string const &target) { 

    if (pat.size() > target.size())
        return std::string::npos;

    size_t max = target.size()-pat.size()+1;

    for (size_t start =0; start < max; ++start) {
        size_t pos;
        for (pos=0; pos < pat.size(); ++pos)
            if (pat[pos] != '?' && pat[pos] != target[start+pos])
                break;
        if (pos == pat.size())
            return start;
    }
    return std::string::npos;
}

#ifdef TEST
#include <iostream>

int main() { 
    std::cout << match("??cd?", "aaaacdxyz") << "\n";
    std::cout << match("?bc", "abc") << "\n";
    std::cout << match("ab?", "abc") << "\n";
    std::cout << match("ab?", "xabc") << "\n";
    std::cout << match("?cd?", "cdx") << "\n";
    std::cout << match("??cd?", "aaaacd") << "\n";
    std::cout << match("??????", "abc") << "\n";
    return 0;
}

#endif

如果您只想根据整个模式是否与整个输入匹配来表示是/否,您可以做几乎相同的事情,但最初测试!= 而不是&gt;,然后基本上删除外循环。

【讨论】:

  • @Alex:如果模式匹配整个字符串,您是否只希望它表示匹配,或者您是否希望(例如)?abcxxxabc 匹配,并告诉您它从第三个位置开始匹配?
【解决方案3】:

或者,如果您坚持以“通配符”的形式显示您要搜索的术语是“glob”(至少在类 unix 系统上)。

以 c 为中心的 API 可以在类 unix 系统上的 glob.h 中找到,它由手册第 3 节中的两个调用 globglobfree 组成。

切换到完整的正则表达式将允许您使用更多的 c++ 方法,如其他答案所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2015-07-29
    • 2016-10-08
    • 2016-02-10
    • 2014-08-01
    相关资源
    最近更新 更多