Removing escape sequences from strings

J

JJ

Is there a way of checking that a line with escape sequences in it, has no
strings in it (apart from the escape sequences)?

i.e. a line with \n\t\t\t\t\t\t\t\r\n would have no string in it
a line with \n\t\t\t\thello\t\t\n would hve the string 'hello' in it.

In others words, is there a method of removing all escape sequences from a
string?

I've tried Regex.Unescape(string) but this doesn't not seem to remove the
sequences.
Is there a way, or do I have to try and remove all the possible excape
sequences by parsing the string?

Thanks,
JJ
 
M

Mark Fitzpatrick

Have you tried just replacing them with nothing? If it's a string you could
do this like myString.Replace("\t","").Replace("\n","")
 
M

Mark Rae

JJ said:
Is there a way of checking that a line with escape sequences in it, has no
strings in it (apart from the escape sequences)?

i.e. a line with \n\t\t\t\t\t\t\t\r\n would have no string in it
a line with \n\t\t\t\thello\t\t\n would hve the string 'hello' in it.

In others words, is there a method of removing all escape sequences from a
string?

I've tried Regex.Unescape(string) but this doesn't not seem to remove the
sequences.
Is there a way, or do I have to try and remove all the possible excape
sequences by parsing the string?


There may be a "cleverer" more efficient way of doing this, but how about:

string strEscaped = "\n\t\t\t\thello\t\t\n";
string strUnescaped = strUnescaped.Replace("\n",
"").Replace("\t","").Replace("\r","");
 
J

JJ

Thats what I ended up doing (string.replace). My worry was that there seems
to be a lot of these possible escape sequences beyond the standard \r \t \n
etc. so I foolishly thought that there might be a 'built-in' method that
removes all possible sequences.

Thanks again,
John
 
M

Mark Rae

My worry was that there seems to be a lot of these possible escape
sequences

In fact, there are only a handful:
http://msdn2.microsoft.com/en-us/library/4edbef7e(VS.80).aspx

Seems like a good candidate for a static method:

public static string StripEscape(string pstrText)
{
string strStrippedText = pstrText;

strStrippedText = strStrippedText.Replace("\t", String.Empty);
strStrippedText = strStrippedText.Replace("\n", String.Empty);

// etc

return strStrippedText;
}

Obviously, the list of escape characters may change in future versions of
C#...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top