Re: Converting a string
Brady Kelly <[email protected]> Fri, 7 Sep 2007 16:08:00 +0200
| Newsgroups | gmane.comp.windows.devel.dotnet.winforms |
|---|---|
| Message-ID | <[email protected]> |
Lovely solution Mike. Would you mind if I blogged it, with full credit of course? > -----Original Message----- > From: Discussion forum for developers using Windows Forms to build apps > and controls [mailto:[email protected]] On Behalf Of > Mike Woodring > Sent: 06 September 2007 06: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