Re: Converting a string
Mike Woodring <[email protected]> Thu, 6 Sep 2007 10:16:38 -0600
| Newsgroups | gmane.comp.windows.devel.dotnet.winforms |
|---|---|
| Message-ID | <007701c7f0a1$4f5eeb10$ee1cc130$@com> |
> 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