How to use Regex in c# for the following situation - c#

I have a textbox in which when the user tries to enter a word the format should only begin with 'PHY' followed by 8 digit numbers.
For example,
The correct format is PHY00000000
In here the first three letters 'PHY' is constant and the next 8 digit numbers vary from 00000000 to 10000000.
How to get this format using regex condition? No other format should be supported.

If you want regular expression for values range from PHY00000000 to PHY10000000, you should use:
PHY[0-1]\d{7}
But I do not like this, as we are trying to interpret value of number using regular expression. I would use them to split this input and interpret it as a number with specified range (then you can easily change this valid range of numbers):
static bool Valid(string input)
{
const string Pattern = #"PHY(\d{8})";
const int Max = 10000000;
var match = Regex.Match(input, Pattern);
if (match.Success)
{
int value = int.Parse(match.Groups[1].Value);
if (value <= Max)
{
return true;
}
}
return false;
}
So you can take Pattern and Max from some configuration etc.

In order to take care of the requirements, the following regex expression will work:
const string match = "PHY(0\d{7}|1(0){7})";
You then can validate the input by a simple method:
bool ValidateInput(string input)
{
var regex = new Regex(match);
return regex.IsMatch(input);
}

Related

Regular expression for checking a number range (with decimals)

I am working on a window form which accepts certain range of value as input. So far, I could only find the range between 0 and 20000.
(20000|[0-9]|0[1-9]|[1-9]\d{0,3})$
Can somebody kindly help me with finding the range between 0.0 and 20479.0 (including decimals)?
As comments suggest, regex is far from ideal in these cases. It can be done though, but get quite complex.
^(?:(?:1?\d{1,4}|20[0-3]\d\d|204[0-6]\d|2047[0-8])(?:\.\d+)?|20479(?:\.0+)?)$
This does it using two outer alternations - one to match the maximum number and optionally any number of zeroes as decimals. The other (first) has several sub-alternations matching the maximum for the different digits, and allowing an optional decimal point and decimals.
1?\d{1,4} Matches 0-19999
20[0-3]\d\d Matches 20000-20399
204[0-6]\d Matches 20400-20469
2047[0-8] Matches 20470-20478
See it here at regex101.
Here is a suggestion that allows numbers between 0 and 20479 with decimals:
^(0?[0-9]{0,4}(?:\.\d+)?|1\d{4}(?:\.\d+)?|20[0-4][0-7][0-8](?:\.\d+)?|20479(?:\.[0-7])?)$
As you can see, it is a bit complex, you may not want to do it with a regex.
Demo on regex101
Explanation
(0?[0-9]{0,4}(?:\.\d+)? between 0.0 and 9999.99 (decimals are optional)
1\d{4}(?:\.\d+)? between 10000.0 and 19999.99 (decimals are optional)
20[0-4][0-7][0-8](?:\.\d+)? between 20000.0 and 2048.99 (decimals are optional)
20479(?:\.[0-7])? between 20479 and 20479.7
Update: Without decimals, you can use:
^(0?[0-9]{0,4}|1\d{4}|20[0-4][0-7][0-8]|20479$
If you expect only integers (.0 at the end) you could try this
Mask is
^((1?[0-9]{0,4})|((20(([0-3][0-9]{0,2})|(4[0-7][0-9])))))$
If you need .0 at the end add \.0 before $. If you need double/decimal than precision/range would be required.
Why would you use a regex that'll be hardly maintainable when you can use real code:
public bool IsValid(string input = "")
{
double inputParsed;
if (!double.TryParse(input, out inputParsed))
return false;
if(inputParsed < 0 || inputParsed > 20479)
return false;
return true;
}
Using regex get two numbers before and after the point.
Then check the numbers to hit the range.
var list = new List<string> { "VB0.0", "VB20479.0", "VB20479.7", "VB20480.0", "VB010000.0", "VB0.8", "VBx.y" };
string pattern = #"(\d+)\.(\d+)";
foreach (var input in list)
{
var m = Regex.Match(input, pattern);
if (m.Success)
{
string value1 = m.Groups[1].Value;
string value2 = m.Groups[2].Value;
bool result = value1.Length <= 5 && int.Parse(value1) <= 20479
&& value2.Length <= 1 && int.Parse(value2) <= 7;
Console.WriteLine(result);
}
else Console.WriteLine(false);
}

c# How do trim all non numeric character in a string

what is the faster way to trim all alphabet in a string that have alphabet prefix.
For example, input sting "ABC12345" , and i wish to havee 12345 as output only.
Thanks.
Please use "char.IsDigit", try this:
static void Main(string[] args)
{
var input = "ABC12345";
var numeric = new String(input.Where(char.IsDigit).ToArray());
Console.Read();
}
You can use Regular Expressions to trim an alphabetic prefix
var input = "ABC123";
var trimmed = Regex.Replace(input, #"^[A-Za-z]+", "");
// trimmed = "123"
The regular expression (second parameter) ^[A-Za-z]+ of the replace method does most of the work, it defines what you want to be replaced using the following rules:
The ^ character ensures a match only exists at the start of a string
The [A-Za-z] will match any uppercase or lowercase letters
The + means the upper or lowercase letters will be matched as many times in a row as possible
As this is the Replace method, the third parameter then replaces any matches with an empty string.
The other answers seem to answer what is the slowest way .. so if you really need the fastest way, then you can find the index of the first digit and get the substring:
string input = "ABC12345";
int i = 0;
while ( input[i] < '0' || input[i] > '9' ) i++;
string output = input.Substring(i);
The shortest way to get the value would probably be the VB Val method:
double value = Microsoft.VisualBasic.Conversion.Val("ABC12345"); // 12345.0
You would have to regular expression. It seems you are looking for only digits and not letters.
Sample:
string result =
System.Text.RegularExpressions.Regex.Replace("Your input string", #"\D+", string.Empty);

How To Convert The String (X cm) To INT (X) X = Number

How To Convert The String (X LE) To INT (X)
X = Number
I used :
Convert.ToInt32(Form1.sendproductprice1)*Convert.ToInt32(Form1.sendamount));
Example :
Form1.sendproductprice1 = "25 LE";
Form1.sendamount = 5;
Then value must be 125
But I got Error "Input string was not in correct format"
Obviously, 25 LE can't be converted to integer like that. You have to separate the number from the text. In this case, you can use
var num = Form1.sendproductprice1.Split(' ')[0];
which basically takes your input, splits it by spaces and takes the first item from the result. Then this will work
Convert.ToInt32(num)*Convert.ToInt32(Form1.sendamount));
Code below should be work:
Convert.ToInt32(Form1.sendproductprice1.Split(' ')[0])*Convert.ToInt32(Form1.sendamount));
You can extract the number from the string with this code (it allows you to extract the number even if it's not at the beggining)
for (int i=0; i< Form1.sendproductprice1.Length; i++)
{
if (Char.IsDigit(Form1.sendproductprice1[i]))
number += Form1.sendproductprice1[i];
}
Then if you do Convert.ToInt32(number) it will work just fine
You could also use regular expressions.
You will first need to separate the characters from the string to be able to convert the number to integer type.
Convert.ToInt32(Form1.sendproductprice1)
Will throw an exception if the string has something other than integers.
In your case (in the example you provided) the string is as follows: "25 LE"
If the delimeter is always a space then its easy:
var test = "25 LE";
var splitted = test.Split(' ');
var digits = splitted[0]; //Will get you the digits only.
If you want to handle whitespace you can use a Regex as well to parse the input
string input = " 25 LE ";
Regex regex = new Regex("\\d+");
Match match = regex.Match(input);
if (match.Success)
{
int number = Convert.ToInt32(match.Value); // number contains 25
}

Simple regex failing test to determine a 3 digit number

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}$

How to get number from a string

I would like to get number from a string eg:
My123number gives 123
Similarly varchar(32) gives 32 etc
Thanks in Advance.
If there is going to be only one number buried in the string, and it is going to be an integer, then something like this:
int n;
string s = "My123Number";
if (int.TryParse (new string (s.Where (a => Char.IsDigit (a)).ToArray ()), out n)) {
Console.WriteLine ("The number is {0}", n);
}
To explain: s.Where (a => Char.IsDigit (a)).ToArray () extracts only the digits from the original string into an array of char. Then, new string converts that to a string and finally int.TryParse converts that to an integer.
you could go the regular expression way. which is normally faster than looping through the string
public int GetNumber(string text)
{
var exp = new Regex("(\d+)"); // find a sequence of digits could be \d+
var matches = exp.Matches(text);
if (matches.Count == 1) // if there's one number return that
{
int number = int.Parse(matches[0].Value);
return number
}
else if (matches.Count > 1)
throw new InvalidOperationException("only one number allowed");
else
return 0;
}
Loop through each char in the string and test it for being a number. remove all non-numbers and then you have a simple integer as a string. Then you can just use int.parse.
string numString;
foreach(char c in inputString)
if (Char.IsDigit(c)) numString += c;
int realNum = int.Parse(numString);
You could do something like this, then it will work with more then one number as well
public IEnumerable<string> GetNumbers(string indata)
{
MatchCollection matches = Regex.Matches(indata, #"\d+");
foreach (Match match in matches)
{
yield return match.Value;
}
}
First write a specification of what you mean by a "number" (integer? long? decimal? double?) and by "get a number from a string". Including all the cases you want to be able to handle (leading/trailing signs? culture-invariant thousands/decimal separators, culture-sensitive thousands/decimal separators, very large values, strings that don't contain a valid number, ...).
Then write some unit tests for each case you need to be able to handle.
Then code the method (should be easy - basically extract the numeric bit from the string, and try to parse it. Some of the answers provided so far will work for integers provided the string doesn't contain a value larger than Int32.MaxValue).

Categories