2013-10-17 32 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); 
    } 
}