RegEx to accept only numbers between 0-9 [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm fairly new to using regex and I've got a problem with the results of this one.
Regex #"^0[0-9]{9,10}$" is accepting spaces between the digits. How to I stop this as I only want digits between 0-9 to be acceptable characters.
The valid result should start with zero and have either 9 or 10 digits (no spaces or any other character is permissible).
All help appreciated.
Here's my code
Regex telephoneExp = new Regex(#"^0[0-9]{9,10}$");
if (telephoneExp.Match(txtTelephoneNumber.Text).Success==false)
{
MessageBox.Show("The telephone number is not valid, it must only contain digits (0-9) and be either 10 or 11 digits in length.");
return false;
}

This works
^0\d{9,10}$
Matches 0, then 9 to 10 digits.
You could also use Regex.IsMatch instead:
Regex telephoneExp = new Regex(#"^0\d{9,10}$");
if (!telephoneExp.IsMatch(txtTelephoneNumber.Text))
{
MessageBox.Show("The telephone number is not valid, it must only contain digits (0-9) and be either 10 or 11 digits in length.");
return false;
}

Have you tried this to check if it's only a number:
^\d*$
UPDATE:
(^0\d{8,9})$
Checks if 9 or 10 digits starting with leading 0

You don't need regex, you can use LINQ:
var text = txtTelephoneNumber.Text;
bool valid = false;
if (!String.IsNullOrEmpty(text))
{
valid = text.First() == '0' &&
9 <= text.Count() && text.Count() <= 10 &&
text.All(c => Char.IsDigit(c));
}
if (!valid)
{
}

Your code is correct but remove empty chars using Trim() function 100% it will working fine,
Regex telephoneExp = new Regex(#"^0[0-9]{9,10}$");
if (telephoneExp.Match(txtTelephoneNumber.Text.Trim()).Success==false)
{
MessageBox.Show("The telephone number is not valid, it must only contain digits (0-9) and be either 10 or 11 digits in length.");
return false;
}

Related

Validating ID Number C#

I am working on this method that validates a student Id number. The credentials of the ID number are; the first character has to be 9, the second character has to be a 0, there can not be any letters, and the number must be 9 characters long. The method will return true if the student id is valid. When I go to test the method manually through main it comes out as true, even when I put in a wrong input. In my code, I have the if statements nested, but I originally did not have them nested. What is a better way to validate the input to align with the credentials of the ID number? Would converting the string into an array be more ideal?
public static bool ValidateStudentId(string stdntId)
{
string compare = "123456789";
if (stdntId.StartsWith("8"))
{
if (stdntId.StartsWith("91"))
{
if (Regex.IsMatch(stdntId, #"^[a-zA-Z]+$"))
{
if (stdntId.Length > compare.Length)
{
if (stdntId.Length < compare.Length)
{
return false;
}
}
}
}
}
You can try regular expressions:
public static bool ValidateStudentId(string stdntId) => stdntId != null &&
Regex.IsMatch(stdntId, "^90[0-9]{7}$");
Pattern explained:
^ - anchor - string start
90 - digits 9 and 0
[0-9]{7} - exactly 7 digits (each in [0..9] range)
$ - anchor - string end
So we have 9 digits in total (90 prefix - 2 digits + 7 arbitrary digits), starting from 90

c# deleting the 0s of an int, but not if it is 20 [duplicate]

This question already has answers here:
How to remove leading zeros using C#
(9 answers)
Closed 5 years ago.
In my string start can be all sorts of numbers (1 until 99), but when the numbers get generated, 1 always get shown like 01. Is there an way to remove that 0, without if the number is 20 that the number get changed to 2?
You can use the String.TrimStart method:
string num = "0001";
num = num.TrimStart('0');
Another solution:
if (start.ElementAt(0) == '0')
start = start.Remove(0, 1);
or shorter:
start = start.ElementAt(0) == '0' ? start.Substring(1) : start;

Extracting text from the middle of a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have the following string that is captured from the DVLA when looking up a car registration details and I need to be able to extract just the numbers from the CC.
"A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 -
PRESENT"
Given that the lentgh of the string can change, is there a way to do this with a sub-string so for example always grab the numbers from before the cc without the space that comes before it? Bare in mind too that this can sometimes be a 3 digit number or a four digit number.
This does the trick:
string input = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
string size;
Regex r = new Regex("(\\d*)cc", RegexOptions.IgnoreCase);
Match m = r.Match(input);
if (m.Success)
{
size = m.Groups[0];
}
It captures every number that is right before cc
If the count of the comma doesn't change you can do following:
string s = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
string ccString = s.Split(',').ToList().Find(x => x.EndsWith("cc")).Trim();
int cc = Int32.Parse(ccString.Substring(0, ccString.Length - 2));
You can use Regex to match a pattern withing the string - so you can return parts of the string that match the given pattern. This Regex pattern will attempt to match parts of the string that fit the following pattern:
\d{1,5} *[cC]{2}
Starts with 1 to 5 digits \d{1,5} (seems sensible for an engine cc value!)
Can then contain 0 or more spaces in between that and cc *
Ends with any combination of 2 C or c [cC]{2}
So you can then use this in the following manner:
string str = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
Match result = Regex.Match(str, #"\d{1,5} *[cC]{2}");
string cc = result.Value; // 1968cc
Here is another solution:
string text = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
string[] substrings = text.Split(',');
string numeric = new String(substrings[1].Where(Char.IsDigit).ToArray());
Console.WriteLine(numeric);
Here is a working DEMO

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

Categories

Resources