- 论坛徽章:
- 0
|
谁比较熟悉C下的正则表达式编程,帮个忙
- ///////////////////////////////////////////////////////////////////////////////
- /// 功能说明 : 对单行进行匹配并返回匹配值
- /// 输入参数 : szLine 行字符串
- /// : szPattern 行模式
- /// 输出参数 : szValue, 若不为NULL,则返回匹配值
- /// 返回值 : bool
- /// 使用说明 :
- ///////////////////////////////////////////////////////////////////////////////
- bool StrMatchLine ( const char *szLine, const char *szPattern, char *szValue )
- {
- int nRet = 0, cFlags = 0; ///<
- regex_t regVar; ///<
- regmatch_t regMatch[1]; ///< 匹配结果
- const size_t nMatch = 1; ///< 1 个MATCH
- char szErr[256] = ""; ///< 错误信息
-
- if ( szLine == NULL || szPattern == NULL )
- return false;
-
- nRet = regcomp ( ®Var, szPattern, cFlags );
- if ( nRet != 0 )
- {
- regerror ( nRet, ®Var, szErr, sizeof(szErr) );
- //TraceLog ( stdout, __LINE__, "", __FILE__, "Pattern : %s, regcomp error %s", szErr );
- }
-
- nRet = regexec ( ®Var, szLine, nMatch, regMatch, 0 );
- if ( nRet == REG_NOMATCH) ///< 不匹配
- {
- regfree(®Var);
- return false;
- }
- else if ( nRet != 0 ) ///< 执行匹配出错
- {
- regerror ( nRet, ®Var, szErr, sizeof(szErr) );
- //TraceLog ( stdout, __LINE__, "", __FILE__, "Line %s, regexec error %s\n", szLine, szErr );
- regfree(®Var);
- return false;
- }
-
- if ( szValue != NULL ) ///< 获取子字符串
- {
- int nLen = regMatch[0].rm_eo - regMatch[0].rm_so;
- strncpy ( szValue, szLine + regMatch[0].rm_so, nLen );
- szValue[nLen] = '\0';
- }
-
- regfree(®Var); /// 释放正则表达式
- return true;
- }
复制代码 |
|