int _tmain(int argc,TCHAR *argv[]) { TCHAR fname[512],line[4096],*p1; TCHAR msg[BREGEXP_MAX_ERROR_MESSAGE_LEN]; FILE *fp; int len,ctr; BREGEXP *rxp = 0; TCHAR dmy[] = _T(" "); setlocale(LC_ALL, ""); if (argc < 2) { _putts (_T("usage /regstr/ [file]\n if omitted assume /usr/dict/words")); return 0; } _tcscpy(fname,_T("/usr/dict/words")); if (argc > 2) _tcscpy(fname,argv[2]); p1 = argv[1]; fp = _tfopen(fname,_T("r")); if (!fp) { _tprintf (_T("file cant open %s\n"),fname); return 0; } BMatch(p1,dmy,dmy+1,&rxp,msg); // compile using dummy if (msg[0]) { _tprintf (_T("parse error %s\n"),msg); return 0; } ctr = 0; while(_fgetts(line,sizeof(line),fp)) { len = _tcslen(line); if (len && (BMatch(p1,line,line+len,&rxp,msg) > 0)) { ctr++; line[len-1] = 0; _putts(line); } } fclose(fp); _tprintf(_T("%ld lines(s) greped\n"),ctr); return 0; }
int BRegExp::match( const string& iTarget, // 対象文字列 const string& iRE, // 正規表現。/abc/ とか // vector<string>* oResult) // [0]は一致した全体、[1]以降は各カッコ。 vector< pair<string, int> >* oResult) // [0]は一致した全体、[1]以降は各カッコ。secondはiTarget中の開始位置 { int nCount = 0; char msg[80]; if ( !iRE.empty() && iRE[0] == 's' ) { // replace ready(iTarget, iRE, "replace"); if (pLastRegExp == NULL) return 0; nCount = BSubst( strLastRegExp.c_str(), strLastString.c_str() + nLastPos, strLastString.c_str() + strLastString.length(), &pLastRegExp, msg); if (nCount) nLastPos = pLastRegExp->endp[0] - strLastString.c_str(); bLastSplit = false; bLastReplace = true; } else { // match ready(iTarget, iRE, "match"); if (pLastRegExp == NULL) return 0; if (bCountMatch) { while (bool bMatch = BMatch(strLastRegExp.c_str(), strLastString.c_str() + nLastPos, strLastString.c_str() + strLastString.length(), &pLastRegExp, msg) == 1) { nLastPos = pLastRegExp->endp[0] - strLastString.c_str(); ++nCount; } } else { bool bMatch = BMatch(strLastRegExp.c_str(), strLastString.c_str() + nLastPos, strLastString.c_str() + strLastString.length(), &pLastRegExp, msg) == 1; if (bMatch) { nLastPos = pLastRegExp->endp[0] - strLastString.c_str(); nCount = 1; if ( oResult != NULL ) { /* vector<string>& v = *oResult; for (int i=0;i <= pLastRegExp->nparens;i++) v.push_back( string(pLastRegExp->startp[i], pLastRegExp->endp[i]) ); */ vector< pair<string, int> >& v = *oResult; for (int i=0;i <= pLastRegExp->nparens;i++) v.push_back( pair<string, int>( string(pLastRegExp->startp[i], pLastRegExp->endp[i]), pLastRegExp->startp[i] - pLastRegExp->startp[0] )); } } } bLastSplit = false; bLastReplace = false; } return nCount; }