Allow user to enter escape characters in a TextBox

2019-06-04 05:13发布

问题:

I have a Windows.Forms.TextBox that I'd like to allow the user to enter escape sequences that are then interpreted as the character they represent.

For example, if the following is entered:

Hello\r\nWorld

I'd like it to be stored as the character array:

   H     e     l     l     o    \r    \n     W     o     r     l     d
0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x0D, 0x0A, 0x57, 0x6F, 0x72, 0x6C, 0x64

Thus far, I'm using the following to handle '\r' and '\n', but I'd also like to be able to handle any other escape sequence, like \u001A (ctrl+z), or \u001B (esc)

string str = txtBox.Text.Replace("\\r","\r").Replace("\\n","\n");

...There has to be a more general way of handling this...

回答1:

You could try to use the System.Text.RegularExpressions.Regex.Unescape static method:

string str = Regex.Unescape(txtBox.Text);

But unfortunately it applicable mainly for Regex control characters.