Search code examples
regexc++-cli

Replace non printable character with octal representation in C++/CLI


I need to replace any non printable character with its octal representation using C++/CLI. There are examples using C# which require lambda or linq.

// There may be a variety of non printable characters, not just the example ones.
String^ input = "\vThis has internal vertical quote and tab \t\v";
Regex.Replace(input,  @"\p{Cc}", ???  );

// desired output string = "\013This has internal vertical quote and tab \010\013"

Is this possible in with C++/CLI?


Solution

  • Not sure if you can do it inline. I've used this type of logic.

    // tested
    String^ input = "\042This has \011 internal vertical quote and tab \042";
    String^ pat = "\\p{C}";
    String^ result = input;
    array<Byte>^ bytes;
    
    Regex^ search = gcnew Regex(pat);
    for (Match^ match = search->Match(input); match->Success; match = match->NextMatch()) {
        bytes = Encoding::ASCII->GetBytes(match->Value);
        int x = bytes[0];
    
        result = result->Replace(match->Value
            , "\\" + Convert::ToString(x,8)->PadLeft(3, '0'));
    }
    
    Console::WriteLine("{0} -> {1}", input, result);