This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
else if (vReadData.Length==14 && vReadData Is Numeric)
{
if (txtIPLoad_MHEBarcode1.Text == "")
{
txtIPLoad_MISBarcode1.Text = vReadData;
txtIPLoad_MHEBarcode1.Focus();
}
else
{
txtIPLoad_MISBarcode2.Text = vReadData;
txtIPLoad_MHEBarcode2.Focus();
}
mMessage("Scan", "Please scan the MHE Barcode!");
return;
}
This is my code for validating a Textbox. I check the condition that the length should be 14 chars. I must also check that the input which comes in variable vReadData must be numeric (only numbers).
Please help me solve this.
I have tried using
else if (Int64.TryParse(vReadData, out num))
but this is not helping me.
Are you looking for a regular expression?
else if (Regex.IsMatch(vReadData, #"^[0-9]{14}$")) {
// vReadData is a string of exactly 14 digits [0..9]
}
Explanation: we have to match two conditions
The string should be exactly 14 characters long
It should be a valid (non-negative) number (I doubt if any negative bar code exits)
After combining both conditions into one we can say that we're looking for a string which consist of 14 digits [0-9] (please notice, that we want [0-9] not \d, since \d in .Net means any digit, including, say Persian ones)
Tests:
string vReadData = #"B2MX15235687CC";
// vReadData = #"12345678901234";
if (Regex.IsMatch(vReadData, #"^[0-9]{14}$"))
Console.Write("Valid");
else
Console.Write("InValid");
Outcome:
InValid
If you uncomment the line you'll get
Valid
Related
I'm writing a program for Uni which requires some basic validation.
I have a textbox which allows the user to input their age. I have successfully written a Regex expression which checks if the value entered into the textbox contains numeric values only and is two characters long:
Regex agePattern = new Regex(#"^[0-9]{1,2}\z$"); // Age entered must be numeric characters only (0-9) and may only be two charaters long
if (agePattern.IsMatch(ageBox.Text) == false)
{
MessageBox.Show("Customer's age is not valid. Age must be in numeric format & can only be two characters long"); // If Regex pattern & entered string DO NOT match - user get's this message
return;
}
else
{
// do something
}
My question is, can I extend my Regex expression to constrain age values between 1 and 99?
I've not written any Regex before and I'm struggling.
Thanks!
How about parsing an integer instead?
bool IsValidAge(string ageString) {
int age;
return int.TryParse(ageString, out age) && age >= 1 && age <= 99;
}
Try this regex:
^[1-9]?[0-9]?\z
Or skip regex, parse the text as int and write a function which decide input is between 1 and 99.
Try this regex:
^[1-9]?[0-9]?\z
This matches an empty input (since both digits are optional) as well as 0. Fewer ? are better:
^[1-9][0-9]?$
Try it with A Better .NET Regular Expression Tester (most other online testers don't allow to specify an empty source).
Is there a way to validate 'live' input field using Regex in C#?
'live' means that I don't validate complete string, I want to validate the string while it's typed.
For example, I want my string to match the next pattern lalala111#alalala123, so I have to check each new char - is it # ? if it's # then is there a # already in the string? if yes, then I return a null, if no, then I return the char. And of course I have to check chars - is it letter or digit? if yes, then ok, if not, then not ok.
I hope you got my idea.
At now I have this code
private char ValidateEmail(string input, int charIndex, char charToValidate)
{
if (char.IsLetterOrDigit(charToValidate) &&
!(charToValidate >= 'а' && charToValidate <='я') &&
!(charToValidate >= 'А' && charToValidate <= 'Я') ||
charToValidate =='#' ||
"!#$%&'*+-/=?^_`{|}~#.".Contains(charToValidate.ToString()))
{
if ((charToValidate == '#' && input.Contains("#")) ||
(!input.Contains("#") && charIndex>=63) ||
(input.Contains("#") && charIndex >= 192))
return '\0';
}
else
{
return '\0';
}
return char.ToUpper(charToValidate);
}
it allows only latin letters with digits and some special characters, and also it allows first part of the string (before #) to have only 64 letters, and the second part (after #) to have only 128 letters, but the code looks ugly, don't it? So I want to do all these checks in one beauty regular expression.
lYou have to use the following code:
Declare this line at top:
System.Text.RegularExpressions.Regex remail = new System.Text.RegularExpressions.Regex(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
next either on button click or leave event pass the following code to check
if (textemail.Text != "" && !remail.IsMatch(textemail.Text))
{
errorProvider1.Clear();
textemail.Focus();
errorProvider1.SetError(textemail, "Wrong Email ID");
MessageBox.Show("Wrong Email ID");
textemail.SelectAll();
return;
}
After a character has been typed, you want the string that has been entered to match one of the following:
between 1 and 64 (inclusive) acceptablecharacters.
between 1 and 64 (inclusive) acceptable characters then an # character.
between 1 and 64 (inclusive) acceptable characters then an # character then 128 or fewer acceptable characters.
Note that the last two clauses can be combined to say:
between 1 and 64 (inclusive) acceptable characters then an # character then between 0 and 128 inclusive acceptable characters.
Hence the entire requirement can be expressed as:
between 1 and 64 (inclusive) acceptable characters, optionally followed by an # character then between 0 and 128 inclusive acceptable characters.
Where the definition of "acceptable characters" is not at all clear from the question. The code within ValidateEmail does range checks of 'a' to 'я' and of 'А' to 'Я'. It also checks "!#$%&'*+-/=?^_{|}~#.".Contains(...)`.
The text below assumes acceptable characters actually means the 26 letters, upper and lower case, plus the 10 digits.
The required regular expression is then ^\w{1,64}(#\w{0,128})?$
This regular expression can then be used to check the concatenation of the already validated input text plus the character just typed.
If additional characters are wanted to be considered as acceptable then change the \w, there are two of them. For example if underscores (_) and hyphens (-) are to be allowed then change both \ws to be [\w_-].
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
Im working on an assignment for class and it includes using some checks for input to ensure valid input is given, using a regex expression. The example given for the IsValidNumber check is string regex = #"^-?\\d*(\\.\\d+)?$";
I'm not really sure if this is actually checking for valid numbers because i've never seen that before. Wouldn't something like string regex = #"^[0-9]\d*$ work or am i missing something? Note I do need to be able to pass through a float and not just an int.
UPDATE:
Using the regex I was provided, i ran the program only to run into an issue with the error check that didn't allow anything to pass through even if valid
Here is the method that is calling IsNumberValid
private static string GetNumericInput(string c)
{
do
{
Console.Write(c);
string var = Console.ReadLine();
if (!String.IsNullOrEmpty(var) && IsValidNumber(var))
{
return var;
}
else
{
Console.WriteLine("Input was either Null/Empty, or contained non-numeric characters.");
Console.WriteLine("Retry input.");
Console.WriteLine();
}
}
while (true);
}
and here is IsValidNumber
public static bool IsValidNumber(string value)
{
string regex = #"^-?\\d*(\\.\\d+)?$";
return Regex.IsMatch(value, regex);
}
I'm not entirely sure how to read breakpoints for errors but when i put breakpoints at string regex = #"^-?\\d*(\\.\\d+)?$"; and return Regex.IsMatch(value, regex); it shows value for regex as null and "^-?\\d*(\\.\\d+)?$" respectively.
The regex is taking into consideration the decimal point, i.e. it matches not just integers but also floating point numbers. This is what the \\. catches. Also the ^-? matches a possible negative sign. ^[0-9]\d* only matches positive integers.
The statement string regex = #"^-?\\d*(\\.\\d+)?$"; creates a regex pattern that's literally ^-?\\d*(\\.\\d+)?$ because of the # at the front of the string. You don't need to use double backslashes in this case, simply:
string regex = #"^-?\d*(\.\d+)?$";
In addition to #manouti answer of this regex takes in consideration floating point numbers as well, it also takes in account for negative numbers
EDIT 2:
Yes like I thought, i need to change the pattern to 2 different ones, because the OR will make a match for 13 digits a match for 8 digits one
THE SOLUTION IS:
Regex EAN8 = new Regex(#"\b\d{8}\b");
Regex EAN13 = new Regex(#"\d{13}\b");
PS FOR EDIT2: As someone said, problaly in the future i will end up finding EAN1234567890123 or EAN_1234567890123, these patterns wont work out, and I have no idea where to start searching for a pattern like this.
I'm doing a project where I need to take multiple EANs from a text.
I already have a validation class to see if they are valid or not.
And I can take the 13 digits one (but I think the pattern I'm using is not correct and will give problems sooner or later.
Example of a string: "OL‐120 112 82 Estuchado, fácil apertura. 8410032002279 227 24"
as you can see there is a valid EAN13 in the middle: "8410032002279"
I'm using this pattern:
Regex EAN13 = new Regex(#"\d{13}");
It gives me the EAN inside the string, but I think the correct pattern should be like this:
Regex EAN13 = new Regex(#"\d{13}$");
But when I use it it doesn't work. probably because the string doesn't end there.
I have a similar problem with the EAN of 8 digits, if i use this pattern:
Regex EAN8 = new Regex(#"\d{8}");
It gives me the 13 digit eans cut to 8...
What should I do to make both patterns work whatever the position of the EAN is in the string and for the 8 digit return only a real string with 8 digits and not one with more cut down to 8.
Thanks in advance
EDIT: Further Code to understand what I'm doing
Regex EAN = new Regex(#"\b(?:\d{8}|\d{13})\b");
using (StreamReader sr = new StreamReader(#"....txt"))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
Match m13 = EAN.Match(currentLine);
Match m8 = EAN.Match(currentLine);
if (m8.Success)
{
lista_EAN8.Add(m8.Value);
//string valido8 = new Ean8Validate().ValidateEan8(m8.Value);
//if (valido8 == m8.Value)
//{
// lista_EAN8.Add(m8.Value);
//}
}
if (m13.Success)
{
string valido13 = new Ean13Validate().ValidateEan13(m13.Value);
if (valido13 == m13.Value)
{
lista_EAN13.Add(m13.Value);
}
}
}
}
Like this it returns me the same values in list of 13 digit eans and list of 8 digits eans
ok looks like you want 2 different Regexs one for targeting only 8 digit matches and the other for targeting 13 digit matches
for matching of the 8 digit EANs use;
\b(?:\d{8})\b
for matching and for 13 digit EANs use;
\b(?:\d{13})\b
additionally is you want an options prefix of EAN(upper or lowercase) you can use;
for 8 digit
\b(?:[Ee][Aa][Nn])?(?:\d{8})\b
for 13 digit
\b(?:[Ee][Aa][Nn])?(?:\d{8})\b
for your example you want to modify the code so it read something like this.
Regex EAN8 = new Regex(#"\b(?:\d{8})\b");
Regex EAN13 = new Regex(#"\b(?:\d{13})\b");
using (StreamReader sr = new StreamReader(#"....txt"))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
Match m13 = EAN13.Match(currentLine);
Match m8 = EAN8.Match(currentLine);
if (m8.Success)
{
lista_EAN8.Add(m8.Value);
}
if (m13.Success)
{
lista_EAN13.Add(m13.Value);
}
}
}
now if we tweek the Regexs a little more we can extract just the number parts out of EAN numbers even when they are prefixed with EAN* or EAN_*
Regex EAN8 = new Regex(#"\b(?:[Ee][Aa][Nn]_?)?(\d{8})\b");
Regex EAN13 = new Regex(#"\b(?:[Ee][Aa][Nn]_?)?(\d{13})\b");
using (StreamReader sr = new StreamReader(#"....txt"))
{
string currentLine;
while ((currentLine = sr.ReadLine()) != null)
{
Match m13 = EAN13.Match(currentLine);
Match m8 = EAN8.Match(currentLine);
if (m8.Success)
{
lista_EAN8.Add(m8.Groups[1].Value);
}
if (m13.Success)
{
lista_EAN13.Add(m13.Groups[1].Value);
}
}
}
this will capture the number part while throwing away the EAN prefix
Use the below regex to match 8 or 13 digits. \b is a word boundary which matches between a word character and a non-word character. So it avoids matching 8 digit number in a 13 digit number.
\b(?:\d{8}|\d{13})\b
Try this regex string. \b = word boundary and the | makes sure that it will only match 8 or 13 and not some number in between:
\b\d{8}\b|\b\d{13}\b
If you want dob't allow unicode digit use character class instead shortcut \d ( it's much faster)
\b(?:[0-9]{8}|[0-9]{13})\b
I managed to concoct this:
\b(([Ee][Aa][Nn])?[_]?([0-9]{13}|[0-9]{8}))\b
This part ([Ee][Aa][Nn])? groups the case-insensitive sequence EAN and makes it optional with ?
Then [_]? makes the underscore optional. I added the square brackets for prettiness sake
The digits are identified using their character representation [0-9]{13} and [0-9]{8}
Everything is wrapped up in a \b( ... )\b block to identify the word boundary
The two EAN types are wrapped by parentheses and separated by an OR |
Below is a screenshot from http://regexpal.com/ showing the testing set and the matching.
Jorge, I must say I don't like repeating code, (or anything else for that matter :D ). I am therefore not very fond of the whole ([Ee][Aa][Nn])?[_]? appearing twice. Moreover if tomorrow you wish to look for EAN5 for example you must further copy it and the regexp becomes ever more ugly.
Here is what I had before the cleanup:
\b(([Ee][Aa][Nn])?[_]?[0-9]{13}|([Ee][Aa][Nn])?[_]?[0-9]{8})\b
Below is a screenshot from http://regexpal.com/ showing the testing set and the matching.
I have had a difficult time wrapping my head around regular expressions. In the following code, I used a Regex to determine if the data passed was a 1 to 3 digit number. The expression worked if the data started with a number (ex. "200"), but also passed if the data had a letter not in the first digit (ex. "3A5"). I managed to handle the error with the INT32.TryParse() method, but it seems there should be an easier way.
if (LSK == MainWindow.LSK6R)
{
int ci;
int length = SP_Command.Length;
if (length > 3) return MainWindow.ENTRY_OUT_OF_RANGE; //Cannot be greater than 999
String pattern = #"[0-9]{1,3}"; //RegEx pattern for 1 to 3 digit number
if (Regex.IsMatch(SP_Command, pattern)) //Does not check for ^A-Z. See below.
{
bool test = Int32.TryParse(SP_Command, out ci); //Trying to parse A-Z. Only if
if (test) //it no letter will it succeed
{
FlightPlan.CostIndex = ci; //Update the flightplan CI
CI.Text = ci.ToString(); //Update the Init page
}
else return MainWindow.FORMAT_ERROR; //It contained a letter
}
else return MainWindow.FORMAT_ERROR; //It didn't fit the RegEx
}
Regex.IsMatch searches the input string for the pattern (and thus returns true for 3A5 because it finds 3).
You should also include start (^) and end ($) of string:
String pattern = #"^[0-9]{1,3}$";
Adding line begin/end should help.
^[0-9]{1,3}$