c# string format validate - c#

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.

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#.

Related

numeric format strings #,#0.00 vs #,0.00

I tried to figure out the basics of these numeric string formatters. So I think I understand the basics but there is one thing I'm not sure about
So, for example
#,##0.00
It turns out that it produces identical results as
#,#0.00
or
#,0.00
#,#########0.00
So my question is, why are people using the #,## so often (I see it a lot when googling)
Maybe I missed something.
You can try it out yourself here and put the following inside that main function
double value = 1234.67890;
Console.WriteLine(value.ToString("#,0.00"));
Console.WriteLine(value.ToString("#,#0.00"));
Console.WriteLine(value.ToString("#,##0.00"));
Console.WriteLine(value.ToString("#,########0.00"));
Probably because Microsoft uses the same format specifier in their documentation, including the page you linked. It's not too hard to figure out why; #,##0.00 more clearly states the programmer's intent: three-digit groups separated by commas.
What happens?
The following function is called:
public string ToString(string? format)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
It is important to realize that the format is used to format the string, but your formats happen to give the same result.
Examples:
value.ToString("#,#") // 1,235
value.ToString("0,0") // 1,235
value.ToString("#") // 1235
value.ToString("0") // 1235
value.ToString("#.#")) // 1234.7
value.ToString("#.##") // 1234.68
value.ToString("#.###") // 1234.679
value.ToString("#.#####") // 1234.6789
value.ToString("#.######") // = value.ToString("#.#######") = 1234.6789
We see that
it doesn't matter whether you put #, 0, or any other digit for that matter
One occurrence means: any arbitrary large number
double value = 123467890;
Console.WriteLine(value.ToString("#")); // Prints the full number
, and . however, are treated different for double
After a dot or comma, it will only show the amount of character that are provided (or less: as for #.######).
At this point it's clear that it has to do with the programmer's intent. If you want to display the number as 1,234.68 or 1234.67890, you would format it as
"#,###.##" or "#,#.##" // 1,234.68
"####.#####" or "#.#####" // 1234.67890

Regex for mobile number with special characters in c#

I'm trying to build a regular expression to validate mobile numbers that accepts (),- and +. I am totally new to this and this is what I could build
\+?\(?([0-9])\)?[- ]?\(?([0-9])\)?
But I know this wrong since it is accepting data such as 123456- which is not right.
Can somebody please help me build a regex so that itdoes not accept inputs like
123)3575
12349-
-2345678
There is no limit to the number of digits entered. I'm expecting it to accept inputs of type
(123)4567-67898
+234567890
1234-4567-67
Please help..
Something like
/^(\+|\(\d+\))?\d+(-\d+)*$/
Regex Demo
Test
Regex.IsMatch("(123)4567-67898", #"^(\+|\(\d+\))?\d+(-\d+)*$");
=> True
Regex.IsMatch("-2345678", #"^(\+|\(\d+\))?\d+(-\d+)*$");
=> False

Reverse RegExp from user entered string ( C#)

Is it possible to generate regular expressions from a user entered string? Are there any C# libraries to do this?
For example a user enters a string e.g. ABCxyz123 and the C# code automatically generates [A-Z]{3}[a-z]{3}\d{3}.
This is a simple string but we could have more complicated strings like
MON-0123/AB/5678-abc 2/7
Or
1234-678/abc::1234ABC?246
I already have a string tokeniser (from a previous stackoverflow question) so I could construct a regex from the list of tokens.
But I was wondering if there is a lib or C# code out there that’ll do it.
Edit: Important, I should of also said: It's not the actual character in the string that are important but the type of character and how many.
e.g A user could enter a "pattern" string of ABCxyz123.
This would be interpreted as
3 upper case alphas followed by
3 lower case alphas followed by
3 digits
So other users (when complied) must enter strings that match that pattern [A-Z]{3}[a-z]{3}\d{3}., e.g. QAZplm789
It's the format of user entered strings that's need to be checked not the actual content if that makes sense
Jerry has a related link
creating a regular expression for a list of strings
There are a few other links off this.
I'm not trying to do anything complicated e.g NLP etc.
I could use C# expression builder and dynamic linq at a push, but that seems overkill and a code maintainable nightmare .
I'll write my own "simple" regex builder from the tokenized string.
Example Use Case:
An admin office user where I work could setup the string patterns for each field by typing a string pattern, My code converts this to a regex, I store these in a database.
E.g: Field one requires 3 digits at the start. If there are 2 digits then send to workflow 1 if 3 then send to workflow 2. I could simply check the number of chars by substr or what ever. But this would be a concrete solution.
I am trying to do this generically for multiple documents with multiple fields. Also, each field could have multiple format checkers.
I don't want to write specific C# checks for every single field in numerous documents.
I'll get on with it, should keep me amused for a couple of days.

string to double validation c# please answer

ok so I am building a program in WPF format.
as you know wpf's inputs are usually string, to turn those into double first I need to validate if those string fit and then to proceed and convert them.
the problem is in the validation, I have done the part in the validation that is checking if the string.IsNullOrEmpty but the thing I could not do is validate if the answer is completely not convertable... let me show an example because some strings that are not completely numeric are still should be accepted for example:
"sadasdaasd" - not accepted (obviously)
"8945a4554" - not accepted (there is an 'a' in the middle)
"3519" - accepted
"12.55" - accepted
"-3/4" - accepted and the value should be converted to double as (-3) divided by (4). so '/' is accepted and it splits the string by 2 and then converts it to double as first part/ second part.
I have been trying to do this validation all day and still have not succeeded, I have tried searching the web for some input validation, some said that I need to use double.TryParse(string, out double) but this function does not work with the '/' split that i wanted. so please help me!!!
I would start by parsing your string via regex (q: is "-3*4" acceptable as -3 times 4?). Basically you're looking for a match on a regex which is kind of like this (this works on -3/4, you'd want to test it further and modify if multiplication is allowed): -?\d+[/]\d+
If you find that match, parse out your string with string.Split('/') which will give you an array of strings. TryParse each of those and do the math.
If there is not a match, use TryParse (as recommended previously). That will either succeed (3519, 12.55 in your examples) or fail (sadasdaasd, 8945a4554 in your examples).
Note: you could also use string.Contains('/'), but then you have to check to see if it holds more than one slash (unless such a thing is allowed- in which case you'll need to revisit that regex).

custom string format puzzler

We have a requirement to display bank routing/account data that is masked with asterisks, except for the last 4 numbers. It seemed simple enough until I found this in unit testing:
string.Format("{0:****1234}",61101234)
is properly displayed as: "****1234"
but
string.Format("{0:****0052}",16000052)
is incorrectly displayed (due to the zeros??): "****1600005252""
If you use the following in C# it works correctly, but I am unable to use this because DevExpress automatically wraps it with "{0: ... }" when you set the displayformat without the curly brackets:
string.Format("****0052",16000052)
Can anyone think of a way to get this format to work properly inside curly brackets (with the full 8 digit number passed in)?
UPDATE: The string.format above is only a way of testing the problem I am trying to solve. It is not the finished code. I have to pass to DevExpress a string format inside braces in order for the routing number to be formatted correctly.
It's a shame that you haven't included the code which is building the format string. It's very odd to have the format string depend on the data in the way that it looks like you have.
I would not try to do this in a format string; instead, I'd write a method to convert the credit card number into an "obscured" string form, quite possibly just using Substring and string concatenation. For example:
public static string ObscureFirstFourCharacters(string input)
{
// TODO: Argument validation
return "****" + input.Substring(4);
}
(It's not clear what the data type of your credit card number is. If it's a numeric type and you need to convert it to a string first, you need to be careful to end up with a fixed-size string, left-padded with zeroes.)
I think you are looking for something like this:
string.Format("{0:****0000}", 16000052);
But I have not seen that with the * inline like that. Without knowing better I probably would have done:
string.Format("{0}{1}", "****", str.Substring(str.Length-4, 4);
Or even dropping the format call if I knew the length.
These approaches are worthwhile to look through: Mask out part first 12 characters of string with *?
As you are alluding to in the comments, this should also work:
string.Format("{0:****####}", 16000052);
The difference is using the 0's will display a zero if no digit is present, # will not. Should be moot in your situation.
If for some reason you want to print the literal zeros, use this:
string.Format("{0:****\0\052}", 16000052);
But note that this is not doing anything with your input at all.

Categories