華為編程大賽—含有萬用字元的字串匹配問題—基於Regex

來源:互聯網
上載者:User

 問題描述
判斷包含萬用字元的匹配字串是否完全符合輸入的字串,匹配字串中包含的萬用字元僅有‘ * ’和‘?’,且萬用字元不會連續出現 。(要求完全符合,而不是包含)
其中,萬用字元‘ * ’:代替 0 個或多個字元,萬用字元‘ ? ’:代替一個字元
 要求實現函數
int GetMatchSta (const char *ArrStr, const char *KeyStr)
【輸入】 ArrStr :    給定的字串
         KeyStr :       包含萬用字元的匹配字串
【輸出】 無
【返回】是否匹配,匹配返回1 ,不匹配返回0
l  樣本
輸入: ” abcdefg”, “a*”
返回: 1
 
輸入: “tommababcabc” , t?m*ab*abc

返回: 1

參考了《代碼之美》第一章---Regex匹配器 :http://blog.chinaunix.net/uid-26822401-id-3150018.html

#include <iostream>#include <cstring>using namespace std;int GetMatchSta (const char *ArrStr,const  char *KeyStr);int matchhere(const char *arrstr,const char *keystr);int matchstar(const char *arrstr,char ch,const char *keystr);//處理 * 的情況 int main(){char *arr="tommababcabc";char *key="t?m*ab*abc";cout<<GetMatchSta(arr,key)<<endl; } int GetMatchSta (const char *ArrStr,const char *KeyStr){if(KeyStr[0]=='*' && KeyStr[1]!='\0' && KeyStr[1]!='?')return matchstar(ArrStr,KeyStr[1],KeyStr+1);if(KeyStr[0]=='*' && (KeyStr[1]=='?'))// "*?" 這種情況匹配所有除非源串為空白 return strlen(ArrStr)!=0;if(KeyStr[0]=='*' && KeyStr[1]=='\0') // "*" 這情況匹配所有,包括空串 return 1;if(KeyStr[0]=='?')return matchhere(ArrStr+1,KeyStr+1);return matchhere(ArrStr,KeyStr); }int matchhere(const char *arrstr,const char *keystr){if(keystr[0]=='\0')return *arrstr=='\0';if(keystr[0]=='*')return matchstar(arrstr,keystr[1],keystr+1);if(*arrstr!='\0' && (keystr[0]==arrstr[0] || keystr[0]=='?'))return matchhere(arrstr+1,keystr+1);return 0;}int matchstar(const char *arrstr,char ch,const char *keystr){if(ch=='\0') return 1;   //以 * 結尾 do{if(matchhere(arrstr,keystr))return 1;} while( *arrstr++ !='\0');return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.