Seine
Seine

Reputation: 3

c# string format validate

Update: The acceptable format is ADD|| . I need to check if the request that the server gets, is in this format, and the numbers are between <>. After that I have to read the numbers and add them and write the result back. So, if the format not fits to for example ADD|<5>|<8> I have to refuse it and make a specific error message(it is not a number, it is wrong format, etc.). I checked the ADD| part, I took them in an array, and I can check, if the numbers are not numbers. But I cannot check if the numbers are in <> or not, because the numbers can contain multiple digits and ADD|<7>|<13> is not the same number of items likeADD|<2358>|<78961156>. How can I check that the numbers are in between <>?

please help me with the following: I need to make a server-client console application, and I would like to validate requests from the clients. The acceptable format is XXX|<number>|<number>. I can split the message like here:

string[] messageProcess = message.Split('|');

and I can check if it is a number or not:

if (!(double.TryParse(messageProcess[1], out double number1)) || !(double.TryParse(messageProcess[2], out double number2)))

but how can I check the <number> part? Thank you for your advice.

Upvotes: 0

Views: 1105

Answers (1)

Asunez
Asunez

Reputation: 2347

You can use Regex for that.

If I understood you correctly, follwing inputs should pass validation:

xxx|1232|32133
xxx|5345|23423
XXX|1323|45645

and following shouldn't:

YYY|1231|34423
XXX|ds12|sda43

If my assumptions are correct, this Regex should do the trick:

XXX\|\d+\|\d+

What it does?

  • first it looks for three X's... (if it doesn't matter if it's uppercase or lowercase X substitute XXX with (?:XXX|xxx) or use "case insensitive regex flag" - demo)
  • separated by pipe (|)...
  • then looks for more than one digit...
  • separated by pipe (|)...
  • finally ending with another set of one or more digits

You can see the demo here: Regex101 Demo

And since you are using C#, the Regex.IsMatch() would probably fit you best. You can read about it here, if you are unfamiliar with regular expressions and how to use them in C#.

Upvotes: 1

Related Questions