Search code examples
regexvisual-c++mfcc-strings

How to you regex to extract just the name from a CString?


Take a CString that has the following definition:

CString strNameText = _T("Mr Happy [12]");

I have a series of names with all have the space with a number is brackets at the end. Now I want to extract just the name from the string.

I realise that I can find the first index of " [" and then extract the text on the left up to that index. But can I use any regex command to do the same?


Solution

  • I might suggest a regex replacement here, to remove the bracketed term at the end of the string.

    std::string strNameText ("Mr Happy [12]");
    std::regex r ("\\s+\\[\\d+\\]$");
    std::cout << std::regex_replace (strNameText, r, "");  // Mr Happy
    

    C++ Example

    #include <regex>
    
    CString strNameText = _T("Mr Happy [12]");
    
    std::string s1 = CT2A(strNameText);
    std::regex r("\\s+\\[\\d+\\]$");
    std::string s2 = std::regex_replace(s1, r, "");
    
    return CString(s2.c_str());