Regex condition in C# - c#

I have state numbers and state letters of vehicles according to States in DB. State numbers can be old and new type.
Example of new types of state number.
273KL01
002UK02
098KZ03
120US04
...
Example of old types of state number.
R575KMM
A887KDN
M784LKA
X647DUA
...
Bold characters indicates specified State.
User will input his car's state number and choose State. I need to validate If state number can be registered in chosen State. If it not possible(wrong user input) I will show him message like "You entered wrong state number or State" .
I have done this with If-Else statement. But I want to know another way with regex.
As I think, here will be two steps of condition.
Check if number is old type(starts with letter), if true get from DB state letter and check with regex statements.
If case 1 is false, I get from DB state digits and check with regex statements.
I have regex statement for the first condition:
^(?i)f - Where state letter is f.
What will be regex statement for my second conditon?
Or can be it done(two steps both) with one regex statements?

As you further explained that you actually do want to match any letter at the beginning, and any two digits at the end of the string, using a regular expression is indeed the shortest way to solve this.
Regex re = new Regex("^[a-z].*[0-9]{2}$", RegexOptions.IgnoreCase);
Console.WriteLine(re.IsMatch("Apple02")); // true
Console.WriteLine(re.IsMatch("Arrow")); // false
Console.WriteLine(re.IsMatch("45Alty12")); // false
Console.WriteLine(re.IsMatch("Basci98")); // true
Otherwise, if your requirement is simple, e.g. just the letter A or a at the beginning, and 12 or 02 at the end, then you can also solve this easily without regular expressions:
bool Match(string s)
{
if (string.IsNullOrWhiteSpace(s))
return false;
if (s[0] != 'a' && s[0] != 'A')
return false;
return s.EndsWith("02") || s.EndsWith("12");
}
Examples:
Console.WriteLine(Match("Apple02")); // true
Console.WriteLine(Match("Arrow")); // false
Console.WriteLine(Match("45Alty12")); // false
Console.WriteLine(Match("a12")); // true
Console.WriteLine(Match("a")); // false
Console.WriteLine(Match("12")); // false
Of course you can also expand this to fit your more complex requirement. In your case, you could use char.IsLetter and char.IsDigit to make the checks:
bool Match(string s)
{
if (string.IsNullOrWhiteSpace(s))
return false;
return s.Length > 2 && char.IsLetter(s[0]) &&
char.IsDigit(s[s.Length - 1]) && char.IsDigit(s[s.Length - 2]);
}
Note that the IsLetter method also accepts letters from non-English alphabets, so you might need to change that. You could alternatively make a comparison like this:
bool Match(string s)
{
if (string.IsNullOrWhiteSpace(s))
return false;
return s.Length > 2 &&
((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z'))
char.IsDigit(s[s.Length - 1]) && char.IsDigit(s[s.Length - 2]);
}

Here's what you need:
^[Aa].*[01][2]$
With a few explanations:
^ assert position at start of a line
[Aa] match a single character present in the list below
Aa a single character in the list Aa literally
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[01] match a single character present in the list below
01 a single character in the list 01 literally
[2] match a single character present in the list below
2 the literal character 2
$ assert position at end of a line
If you need it to start with any letter :
^[A-Za-z].*[01][2]$
Given your edit:
I would use this regex:
^[A-Z].{6}|.{5}\d{2}$
Which guaranties that the input is:
Of length 7;
Start with a capital letter OR finishes with two digit

Related

Validate String With Regex

I'm trying to validate a string with this regex
var regexAgencia = new Regex("^(?!0000)([0-9]{4})");
var result = regexAgencia.IsMatch(agencia);
Valid Options:
N-X
NN-X
NNN-X
NNNN-X
N
NN
NNN
NNNN
Invalid Options:
0-X
00-X
000-X
0000-X
0
00
000
0000
Where N is any number 0-9 and X can be X or 0-9
When I validade this "014777417" the regex return true
I need help to write a regex to validade this string with this rules.
This should do it for you:
^(?=\d*[1-9])\d{1,4}(?:-[X\d])?$
It starts with a positive look ahead to ensure a digit other than zero is present ((?=\d*[1-9])). Thereafter it matches 1-4 digits, optionally followed by a hyphen and a digit or X.
See it here at regex101.
You certainly can do this through just Regex, however, I always have this lingering fear of creating code that either:
1) only I understand or remember
2) even I don't understand when looking back
In that spirit, it seems if you do a simple split, your string might be easier to evaluate:
string[] parts = agencia.Split('-');
if ((parts.Length == 1 && Regex.IsMatch(agencia, #"^\d{1,4}$")) ||
(parts.Length == 2 && Regex.IsMatch(parts[0], #"^\d{1,4}$")) &&
Regex.IsMatch(parts[1], #"^[0-9X]$"))
{
}
-- EDIT --
I can't tell if you want 0 or not, so if you don't, change \d from to [1-9].
It would be easier to have two tests: one to check if it could be valid, followed by one to exclude the special case of all leading zeros being invalid:
static void Main(string[] args)
{
string[] agencias = { "", "1234-5", "0-9", "014777417", "0000", "1-23", "01-0", "1-234 abcd", "0123-4" };
var regexAgenciaValid = new Regex("^(([0-9]{1,4})(-[0-9])?)$");
var regexAgenciaInvalid = new Regex("^((0{1,4})(-[0-9])?)$");
foreach (string agencia in agencias)
{
var result = regexAgenciaValid.IsMatch(agencia) && !regexAgenciaInvalid.IsMatch(agencia);
Console.WriteLine(agencia + " " + result);
}
Console.ReadLine();
}
Output:
False
1234-5 True
0-9 False
014777417 False
0000 False
1-23 False
01-0 True
1-234 abcd False
0123-4 True
This has the bonus of being easier to modify in the future.

Check string for all digits and if any white space using Linq

I'm checking a string value using Linq, if it has all digits using the following query:
bool isAllDigits = !query.Any(ch => ch < '0' || ch > '9');
But if user enters a space, along with digits (eg: "123 456", "123456 ") this check fails. Is there a way that I can check for white spaces as well?
I don't want to trim out the white spaces, because I use this text box to search with text, which contains spaces in between.
Try this:
bool isAllDigits = query.All(c => char.IsWhiteSpace(c) || char.IsDigit(c));
These methods are built into the framework and instead of rolling your own checks, I would suggest using these.
I made a fiddle here to demonstrate.
EDIT
As pointed out in the comments, char.IsDigit() will return true for other "digit" characters as well (i.e not just '0'-'9', but also other language/culture number representations as well). The full list (I believe) can be found here.
In addition, char.IsWhiteSpace() will also return true for various types of whitespace characters (see the docs for more details).
If you want to only allow 0-9 and a regular 'ol space character, you can do this:
bool isAllDigits = s.All(c => (c < 57 && c > 48) || c == 32);
I am using the decimal values of the ASCII characters (for reference), but you could also continue doing it the way you are currently:
bool isAllDigits = s.All(c => (c < '9' && c > '0') || c == ' ');
Either way is fine, the important thing to note is the parentheses. You want any character that is greater than 0, but less than 9 OR just a single space.
bool isAllDigits = !query.Any(ch => (ch < '0' || ch > '9') && ch != ' ');

String validations c#

I have a 9 character string I am trying to provide multiple checks on. I want to first check if the first 1 - 7 characters are numbers and then say for example the first 3 characters are numbers how would I check the 5th character for a letter range of G through T.
I am using c# and have tried this so far...
string checkString = "123H56789";
Regex charactorSet = new Regex("[G-T]");
Match matchSetOne = charactorSetOne.Match(checkString, 3);
if (Char.IsNumber(checkString[0]) && Char.IsNumber(checkString[1]) && Char.IsNumber(checkString[2]))
{
if (matchSetOne.Success)
{
Console.WriteLine("3th char is a letter");
}
}
But am not sure if this is the best way to handle the validations.
UPDATE:
The digits can be 0 - 9, but can concatenate from one number to seven. Like this "12345T789" or "1R3456789" etc.
It'a easy with LINQ:
check if the first 1 - 7 characters are numbers :
var condition1 = input.Take(7).All(c => Char.IsDigit(c));
check the 5th character for a letter range of G through T
var condition2 = input.ElementAt(4) >= 'G' && input.ElementAt(4) <= 'T';
As it is, both conditions can't be true at the same time (if the first 7 chars are digits, then the 5th char can't be a letter).

How to validate using Regex

My Requirement is that
My first two digits in entered number is of the range 00-32..
How can i check this through regex in C#?
I could not Figure it out !!`
Do you really need a regex?
int val;
if (Int32.TryParse("00ABFSSDF".Substring(0, 2), out val))
{
if (val >= 0 && val <= 32)
{
// valid
}
}
Since this is almost certainly a learning exercise, here are some hints:
Your rexex will be an "OR" | of two parts, both validating the first two characters
The first expression part will match if the first character is a digit is 0..2, and the second character is a digit 0..9
The second expression part will match if the first character is digit 3, and the second character is a digit 0..2
To match a range of digits, use [A-B] range, where A is the lower and B is the upper bound for the digits to match (both bounds are inclusive).
Try something like
Regex reg = new Regex(#"^([0-2]?[0-9]|3[0-2])$");
Console.WriteLine(reg.IsMatch("00"));
Console.WriteLine(reg.IsMatch("22"));
Console.WriteLine(reg.IsMatch("33"));
Console.WriteLine(reg.IsMatch("42"));
The [0-2]?[0-9] matches all numbers from zero to 29 and the 3[0-2] matches 30-32.
This will validate number from 0 to 32, and also allows for numbers with leading zero, eg, 08.
You should divide the region as in:
^[012]\d|3[012]
if(Regex.IsMatch("123456789","^([0-2][0-9]|3[0-2])"))
// match

regular expression for 2 string arguments having numeric values with range constraint

I need to validate console input arguments. User can pass only 2 arguments separated by Space.
First argument should be between 1 to 100
Second argument should be between 1 to 750.
I need a regular expression to validate the input. Please help.
Description
this regex will match 1-100 space 1-750
^\b([1-9][0-9]?|100)\b\s+\b([1-9][0-9]?|[1-6][0-9]{2}|7[0-4][0-9]|750)\b$
Expanded
^ match the start of the string
\b match the word boundary
( open capture group 1
[1-9] match any single digit not including zero followed by
[0-9]? match any single digit or no digit
| or
100 match the number one hundred
) close the capture group 1
\b\s+\b require a word break, space, and word break.
( start capture group 2
[1-9] match any single digit not including zero followed by
[0-9]? match any single digit or no digit
| or
[1-6] match any digits 1 thru 6 followed by
[0-9]{2} match two of any digits
| or
7 match a seven followed by
[0-4] match digits 0 thru 4 followed by
[0-9] match any single digit
| or
750 match the number seven hundred and fifty
) close the capture group
\b$ require a word break and end of string.
It sounds like you want a pattern like this:
^(1|[1-9]\d|100)\s+(1|[1-9]\d|[1-6]\d\d|7[0-5]\d)$
However, you are probably better off verifying the inputs via normal integer comparison:
int int1, int2;
if (int.TryParse(param1, out int1) && int.TryParse(param2, out int2))
{
if (int1 >= 1 && int1 <= 100 && int2 >= 1 && int2 <= 750)
{
...
}
}
As others have said, regex isn't the best option, but if you really want to use it, this seems to work...
^(?:100|[1-9]\d?) (?:[1-7](?:[0-4]\d|50)|[1-9]\d?)$
I rather recommend not using regex but something like this:
int a=0,b=0;
if(args.Length != 2){
// not 2 arguments
}else{
if(!int.TryParse(args[0], out a) || !int.TryParse(args[1], out b)){
// not numbers
}else{
if(a < 1 || a > 100 || b < 1 || b > 750){
// out of ranges
}else{
// everything fine
}
}
}
and you'll have your numbers right there.

Categories

Resources