Replacing escapsequences with characters

  • Thread starter Thread starter Christof Nordiek
  • Start date Start date
C

Christof Nordiek

Hi,

i have to interpret a string in wich escape sequences are used to escape
special characters. How can I replace these sequences by the character they
replace?

Escapint rules are:

\ -> \\
: -> \:
" -> \"

so the characters \ : and " are escaped by \

I figured out a solution, but it fails where a douled backslash is followed
by another escape sequence.

Thanks

Christof
 
How about:

public static string Escape(string value)
{
return re.Replace(value, @"\$1");
}
static readonly Regex re = new Regex(@"([\\:\""])",
RegexOptions.Compiled);

?

Marc
 
Marc Gravell said:
How about:

public static string Escape(string value)
{
return re.Replace(value, @"\$1");
}
static readonly Regex re = new Regex(@"([\\:\""])",
RegexOptions.Compiled);

?

Marc

Thanks Marc,

but what i'm actually searching is unescaping not escaping.

Christof
 
Fine - sorry, I thought your rule table was the forwards direction; how
about:

public static string Unescape(string value)
{
return re.Replace(value, @"$2");
}
static readonly Regex re = new Regex(@"(\\)([\\:""])",
RegexOptions.Compiled);

Haven't tested it, though...
 
Christof,

I can't help but think of state processing here. Basically, cycle
through every character in the string. If you come across a slash character
"\", then you put yourself in an "escape sequence" state. The loop
continues, and you process the character according to the state you are in,
and revert the state back (so the loop can process normally) when you have
finished processing the escape sequence.
 
This maybe...

public static string UnEscape(string value)
{
return re.Replace(value, @"$1");
}
static readonly Regex re = new Regex(@"\\(.)",
RegexOptions.Compiled);


Christof Nordiek said:
Marc Gravell said:
How about:

public static string Escape(string value)
{
return re.Replace(value, @"\$1");
}
static readonly Regex re = new Regex(@"([\\:\""])",
RegexOptions.Compiled);

?

Marc

Thanks Marc,

but what i'm actually searching is unescaping not escaping.

Christof
 
Marc Gravell said:
Fine - sorry, I thought your rule table was the forwards direction; how
about:

public static string Unescape(string value)
{
return re.Replace(value, @"$2");
}
static readonly Regex re = new Regex(@"(\\)([\\:""])",
RegexOptions.Compiled);

Haven't tested it, though...

Thank you, seems to work.
What I still don't udnerstand is, why this expression doesn't match the 2.
and 3. char of @"\\\:".

Christof
 
As I understand regex (I'm not an expert) a match is then excluded - i.e. it
matches the first 2 characters, does a replace and keeps looking from the
(orignal) 3rd character.

It gets more confusing if you use greedy matches though...

Marc
 
Back
Top