2013-10-17 30 views
3

我需要一个函数到另一个字符串中找出一个模式字符串考虑到通配符_处理在C++

例如,而一个“通配符”字符,如果给定模式是f__h,那么它应该匹配到字符串catfish

所以基本上,下划线需要能够表示任何字母字符,但我想不出一个办法去做这件事。任何人都有如何做到这一点的想法?

谢谢。

+0

看看这篇文章: http://stackoverflow.com/questions/11276000/how-can-i-use-wildcards-with-stringfind 祝你好运! – asalic

回答

1

出了什么问题:

std::search(
    text.begin(), text.end(), 
    pattern.begin(), pattern.end(), 
    [](char fromText, char fromPattern) { 
     return fromPattern == '_' || fromPattern == fromText; 
    }) 

如果函数返回text.end(),没有匹配。 否则,它将返回一个迭代器到 匹配的第一个字符。

2

使用新的标准C++ 11,您可以使用regex。否则使用boost regex

+0

对于简单的东西有点矫枉过正,不是吗? (如果还有其他的元字符或任何需要变长的东西,我会同意的,但是在这种情况下,仅仅使用带有简单谓词的'std :: search'比将其搜索字符串映射到正则表达式更简单。) –

+0

也许,但现在是一个标准的C++特性,我不认为找到其他非标准解决方案或者给出相同(或更多的努力)来找到适用于这种特定情况的解决方案并不方便:std :: search是一种替代方案,当然,但在不同的方法之间,这是我个人的选择。 – Jepessen

+0

std :: search是另一种标准的选择。在我以前的句子中,人们可以理解相反的...抱歉我的英语不好。 – Jepessen

0

如果你不介意C风格的解决方案,这个工作对我来说:

#include <stdio.h> 
#include <string.h> 

const char * wildcard_strstr(const char * haystack, const char * needle) 
{ 
    int needleLen = strlen(needle); 
    while(*haystack) 
    { 
     const char * needleP = needle; 
     const char * haystackP = haystack; 

     bool match = true; 
     while((*needleP)&&(*haystackP)&&((*needleP == *haystackP)||(*needleP == '_'))) 
     { 
     needleP++; 
     haystackP++; 
     } 
     if ((needleP-needle) == needleLen) return haystack; 
            else haystack++; 
    } 
    return NULL; 
} 

int main(int, char **) 
{ 
    while(1) 
    { 
     char haystack[512]; 
     printf("Input haystack: "); fflush(stdout); 
     fgets(haystack, sizeof(haystack), stdin); 
     haystack[strlen(haystack)-1] = '\0'; // trim newline 

     char needle[512]; 
     printf("Input needle: "); fflush(stdout); 
     fgets(needle, sizeof(needle), stdin); 
     needle[strlen(needle)-1] = '\0'; // trim newline 

     const char * match = wildcard_strstr(haystack, needle); 
     printf("\nNeedle [%s] %s in haystack [%s]\n", needle, match?"IS":"IS NOT", haystack); 
     if (match) printf(" returned match position is %p [%s]\n", match, match); 
    } 
}