Re: Converting a string
"Knowlton, Gerald F." <[email protected]> Thu, 6 Sep 2007 15:27:50 -0400
| Newsgroups | gmane.comp.windows.devel.dotnet.winforms |
|---|---|
| Message-ID | <[email protected]> |
Thanks Mike for your solution and your time. Expressions was the way we
were going until someone here said, "What if a command line holds
something other then the ESC or CR keystrokes??". So we decided that we
better write a routine that will examine the command string for all
possible unprintable characters, hence the following routine...
Private Function ConvertString(StringValue as string) as string
Dim Counter as integer
For Counter = 0 to 255
StringValue = StringValue.Replace("Chr(" & counter &
_ ")",Chr(Counter)
Next Counter
Return StringValue
End Function
Turns out the answer was simple after all.
Thanks again for your solution
-----Original Message-----
From: Discussion forum for developers using Windows Forms to build apps
and controls [mailto:[email protected]] On Behalf Of
Mike Woodring
Sent: Thursday, September 06, 2007 12:17 PM
To: [email protected]
Subject: Re: [DOTNET-WINFORMS] Converting a string
> We can do the following
>
> X = ScaleCommand.Replace("Chr(27)", chr(27))
> X = X.Replace("Chr(13)",chr(13)
>
> And so forth for each unprintable.
>
> The result will be what is needed.
>
> I am now going to look at patterns for a simpler solution.
If you stick with putting "Chr(##)" in the DB, then one approach to a
more
general purpose replacement solution is to use the variation of
Regex.Replace that takes a MatchEvaluator (delegate). Then you can
encode
any arbitrary chr(#) pattern in the data, and the code can simply
convert
all such patterns into their corresponding character codes.
This is in C#, not VB, but it should give you the basic idea:
string newString =
Regex.Replace( inputText,
@"(chr\((?<code>\d+)\))",
delegate(Match m)
{
return
Convert.ToChar(Convert.ToInt32(m.Result("${code}"))).ToString();
},
RegexOptions.IgnoreCase );
The regex pattern matches any occurrence of chr(#) [where # can be 1 or
more
occurrences of 0-9]. For each such match, the delegate supplied will be
invoked. That delegate (shown above as an anonymous method) converts
the
string form of the match (eg: "27") into the corresponding integer
value,
then into the corresponding character value, then back into a string
representation (which is what the match evaluator method must return).
Or, since it sounds like you're going to be using the regex repeatedly
over
the course of your program, you should instead setup the regex once
ahead of
time:
Regex regex = new Regex(@"(chr\((?<code>\d+)\))",
RegexOptions.IgnoreCase);
And then just use that regex instance repeatedly to do the
search/replace
operation:
string newString =
regex.Replace( inputText,
delegate(Match m)
{
return
Convert.ToChar(Convert.ToInt32(m.Result("${code}"))).ToString();
} );
-Mike
Bear Canyon Consulting LLC
http://www.bearcanyon.com
http://www.pluralsight.com/mike