0

I write a converter for user input data, which converts number value strings and ascii characters enclosed in ' ' to hex representation. Number entering works fine with:

string TestText = "lorem, 'C', 127, 0x06, '#' ipsum";
TestText = Regex.Replace(
    TestText, 
    " +\\d{1,3}", 
    (MatchEvaluator)(match => Convert.ToByte(match.Value).ToString("X2")));         
Out.Text = TestText;

But how can I detect ascii chars enclosed in ' ' and convert them to a hex string like: 'C' will be 43 and '+' becomes 2B.

juharr
  • 31,741
  • 4
  • 58
  • 93
af_bln
  • 3
  • 2
  • You don't need to explicitly cast your lambda with `(MatchEvaluator)` – juharr Mar 15 '16 at 11:58
  • 1
    Personally I do not know C#, but using what you have asked to do a quick search in the stack overflow questions, I found these two questions with accepted answers here. [Converting Numbers between hex and dec in C#](http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c) AND [Getting the ascii value of a character in C#](http://stackoverflow.com/questions/5002909/getting-the-ascii-value-of-a-character-in-a-c-sharp-string) Both have accepted answers, both should help you with your problem. – KyleFairns Mar 15 '16 at 12:00
  • 1
    Your regex is capturing the `0` of the `0x06` – xanatos Mar 15 '16 at 12:01
  • xanatox, thx I fix it. – af_bln Mar 15 '16 at 12:07

2 Answers2

0

Basically, you want to match the regular expression '[^']'. This looks for all characters that are not ' but which are enclosed in '.

Then, in your match evaluator, you get the character in the middle, and convert it to a hexadecimal string. To do that, first cast the char to an int and then you can use ToString("x2"):

TestText = Regex.Replace(TestText, "'[^']'",
    (MatchEvaluator)(match => ((int)match.Value[1]).ToString("x2")));
poke
  • 369,085
  • 72
  • 557
  • 602
0

First, you need a RegEx to capture the character inside the 's: "'(.)'"

Then you need to convert that character to its hex equivalent, like so: Encoding.ASCII.GetBytes(match.Groups[1].Value).First().ToString("X2")

so your final code would look like this:

string TestText = "lorem, 'C', 127, 0x06, '#' ipsum '+'";
TestText = Regex.Replace(TestText, @" +\d{1,3}", match => Convert.ToByte(match.Value).ToString("X2"));         
TestText = Regex.Replace(TestText, "'(.)'", match => Encoding.ASCII.GetBytes(match.Groups[1].Value).First().ToString("X2"));
Out.Text = TestText;

Note that, as pointed out in the comments, your RegEx is currently matching the 0 at the beginning of 0x06, which may not be what you want.

Keith Hall
  • 15,362
  • 3
  • 53
  • 71