正则表达式匹配
来源:互联网 发布:什么软件p图好用 编辑:程序博客网 时间:2024/06/05 10:55
题目:请实现一个函数用来匹配包含‘。’和‘*’的正则表达式。模式中的字符‘。’表示任意一个字符,而‘*’拜师它前面的字符可以出现任意次(含0次),匹配是指字符串的所有字符匹配整个模式。例如,字符串“aaa”与模式“a.a”和“ab*ac*a”匹配,但与“aa.a”及“ab*a”均不匹配。
实现代码如下:
#include <stdio.h>
bool matchCore(char* string, char* pattern);
bool match(char* str, char* pattern)
{
if(str == NULL || pattern == NULL)
return false;
return matchCore(str, pattern);
}
bool matchCore(char* str, char* pattern)
{
if(*str == '\0' && *pattern == '\0')
return true;
if(*str != '\0' && *pattern == '\0')
return false;
if(*(pattern + 1) == '*')
{
if(*pattern == *str || (*pattern == '.' && *str != '\0'))
// move on the next state
return matchCore(str + 1, pattern + 2)
// stay on the current state
|| matchCore(str + 1, pattern)
// ignore a '*'
|| matchCore(str, pattern + 2);
else
// ignore a '*'
return matchCore(str, pattern + 2);
}
if(*str == *pattern || (*pattern == '.' && *str != '\0'))
return matchCore(str + 1, pattern + 1);
return false;
}
// ==================== Test Code ====================
void Test(char* testName, char* string, char* pattern, bool expected)
{
if(testName != NULL)
printf("%s begins: ", testName);
if(match(string, pattern) == expected)
printf("Passed.\n");
else
printf("FAILED.\n");
}
int main(int argc, char* argv[])
{
Test("Test01", "", "", true);
Test("Test02", "", ".*", true);
Test("Test03", "", ".", false);
Test("Test04", "", "c*", true);
Test("Test05", "a", ".*", true);
Test("Test06", "a", "a.", false);
Test("Test07", "a", "", false);
Test("Test08", "a", ".", true);
Test("Test09", "a", "ab*", true);
Test("Test10", "a", "ab*a", false);
Test("Test11", "aa", "aa", true);
Test("Test12", "aa", "a*", true);
Test("Test13", "aa", ".*", true);
Test("Test14", "aa", ".", false);
Test("Test15", "ab", ".*", true);
Test("Test16", "ab", ".*", true);
Test("Test17", "aaa", "aa*", true);
Test("Test18", "aaa", "aa.a", false);
Test("Test19", "aaa", "a.a", true);
Test("Test20", "aaa", ".a", false);
Test("Test21", "aaa", "a*a", true);
Test("Test22", "aaa", "ab*a", false);
Test("Test23", "aaa", "ab*ac*a", true);
Test("Test24", "aaa", "ab*a*c*a", true);
Test("Test25", "aaa", ".*", true);
Test("Test26", "aab", "c*a*b", true);
Test("Test27", "aaca", "ab*a*c*a", true);
Test("Test28", "aaba", "ab*a*c*a", false);
Test("Test29", "bbbba", ".*a*a", true);
Test("Test30", "bcbbabab", ".*a*a", false);
return 0;
}
- 正则表达式字符匹配
- 正则表达式 匹配"<"方法!
- 正则表达式匹配规则
- 正则表达式匹配规则
- 正则表达式最小匹配
- 正则表达式匹配字符串
- 正则表达式匹配
- 正则表达式匹配汉字
- 正则表达式匹配规则
- 正则表达式匹配关键字
- 正则表达式多次匹配
- 正则表达式匹配
- 正则表达式匹配汇总
- java:正则表达式匹配
- 正则表达式匹配居民身份证
- 正则表达式匹配次
- 匹配的正则表达式
- 正则表达式匹配
- uva 10118(dp + 回溯)
- Eclipse 右键Refrence 无效的解决方法
- Mongodb杂谈(一)
- 一个程序猿的个人网站00
- 消息推送框架 Comet4J
- 正则表达式匹配
- java.sql.SQLException:ORA-01861:文字和格式字符串不匹配
- Jmeter CSS/'JQuery extractor Match No.(匹配数字的含义)
- 80锁屏清理进程(重点)
- Linux 中 x86 的内联汇编
- 安装使用Kickstart
- 第二篇、Android Supersu 屏蔽权限请求通知 SuReceiver广播
- allocator之rebind
- hdu2602 Bone Collector (01背包裸题)