CRichEditCtrl - RegEx

88 Views Asked by At

How do use RegEx search in RichEditCtrl.


The problem I have is to highlight the first instance of text matching a list of regular expressions (the regular expressions can be duplicate, in that case, first regex matches the first instance and the second the second, and so on).

Since FindText does not support regex, I am trying to get all text starting with index 0, match first regular expression, find the match, and then issue the FindText on the matched text, highlight the matched indices, repeat the search from the matched end index and the next regular expression.

int iSearchStart = 0;
for (auto &regexString : regexStrings) {
    CString text_cstr;
    int txtLength = myRichEdit.GetTextLength();

    // I am getting an exception on second regex on the following statement
    myRichEdit.GetTextRange(iSearchStart, txtLength-iSearchStart, text_cstr);  

    string text = text_cstr;
    std::smatch match;
    std::regex regexObj(regexString);  
    //look for the first match in the text
    string matchedString;
    if (std::regex_search(text, match, regexObj)) {
        matchedString = match.str();

        FINDTEXTEX ft;
        ft.chrg.cpMin = iSearchStart;
        ft.chrg.cpMax = -1;
        //ft.lpstrText = _T(tw.c_str());
        ft.lpstrText = _T(matchedString.c_str());
        int iFound = myRichEdit.FindText(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD, &ft);
        if (iFound != -1) {
            myRichEdit.SetSel(ft.chrgText);
            CHARFORMAT2 cf;
            ::memset(&cf, 0, sizeof(cf));
            cf.cbSize = sizeof(cf);
            cf.dwMask = CFM_BACKCOLOR;
            cf.crBackColor = RGB(255, 160, 160);    // pale red
            myRichEdit.SetSelectionCharFormat(cf);
            iSearchStart = ft.chrgText.cpMax + 1;
        }
    }
}
1

There are 1 best solutions below

0
profaisal On

I found the problem, I though the second param to GetTextRange is length of the text, but it is actually index of the end.

So if I change

myRichEdit.GetTextRange(iSearchStart, txtLength-iSearchStart, text_cstr);  

to

myRichEdit.GetTextRange(iSearchStart, txtLength, text_cstr);  

it works!!

I am keeping the code for community to see one way to use regex with CRichEditCtrl.