0

Here is a snippet that includes my string. \u001b[m\u001b[38;2;85;255;85mActionUtil-1.4.2*\u001b[m\u001b[38;2;255;255;255m The string was returned from an SSH command that I executed. I can't use the string in its current state because it contains ANSI standardized escape sequences. How can I programmatically remove the escape sequences so that the only part of the string remaining is ActionUtil a plugin for a minecraft server i developed the ssh commands returns with the plugin name! Now the problem is that everyone can change the color so i really need something to block every color and every escape sequences

I found a python script that works for me: How can I remove the ANSI escape sequences from a string in python but i need it in c# here is the python script i found:

large_text = '\u001b[m\u001b[38;2;85;255;85mActionUtil-1.4.2*\u001b[m\u001b[38;2;255;255;255m'
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
result = ansi_escape.sub('', large_text)
print(result)

Here is what i tried to do in c#

        private void btnRemove_Click(object sender, EventArgs e)
        {
            string largeText = txtInput.Text;
            string result = RemoveAnsiEscapeSequences(largeText);
            txtOutput.Text = result;
        }
        private string RemoveAnsiEscapeSequences(string input)
        {
            string pattern = @"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])";
            string replacement = "";
            string result = Regex.Replace(input, pattern, replacement);
            return result;
        }
  • This might not be helpful, but a lot of common command line utilities have a switch to force them to output plain text. If you haven’t researched that, it might save you some effort. – padeso Jun 10 '23 at 11:35
  • Duplicate of https://stackoverflow.com/questions/76418453/how-to-remove-ansi-escape-sequences-from-a-string-in-c-sharp Besides, the RemoveAnsiEscapeSequences function you have written works, so I don't see where the problem is – RedStoneMatt Jul 04 '23 at 08:48

0 Answers0