在C ++ / CLI中用八进制表示替换不可打印的字符

时间:2018-01-19 19:36:30

标签: regex c++-cli

我需要使用C ++ / CLI用八进制表示替换任何不可打印的字符。有些使用C#的例子需要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"

使用C ++ / CLI可以实现吗?

1 个答案:

答案 0 :(得分:1)

不确定您是否可以内联。我使用过这种逻辑。

// 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);
相关问题