Regular expression to match numbers between 1-5000 [duplicate] - c#

This question already has answers here:
Using regular expressions to validate a numeric range
(11 answers)
Closed 2 years ago.
I would like to use a regex for a textbox that allows only numbers between 1-5000
I've tried the following but it wont work:
#"/^(?:1|5000|-[1-9]\d?)$/

You can use ^(?:[1-9]|\d{2,3}|[1-4]\d{3}|5000)$. But you'd better to parse to Int then do simple maths.

With some parsing beforehand, you can make the regex very simple:
string s = textBox1.Text;
string r = "";
int n = 0;
if (int.TryParse(s, out n) && (n>=1 && n<=5000))
{
r = "y";
}
if (Regex.IsMatch(r, "y")) {
// input was valid
MessageBox.Show("OK");
}

Try ...
^(?:[1-4][0-9]{1,3}|[1-9][0-9]{0,2}|5000)$

You can do something like the following:
^(([1-4][0-9]{0,3})|([1-9][0-9]{0,2})|(5000))$
The first two groups will match anything in the range of 1 - 4999. You add the |5000 at the end to make it match the range 1 - 5000. The three cases here are:
The number is exactly 5000
The number is between 1 and 3 digits. In this case, it can't possibly be more than 5000. However, the first number must be 1 - 9 so that you can't get something like "009" or "000."
The number is 4 digits, in which case it must be between 1000 - 4999
With that said, I think it would probably be simpler to just parse the int and see if it's in range.

You can try something like this (0-366)
^(0?[0-9]?[0-9]|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-6])$

Related

General questions to regex, conditions and if-statement [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 3 years ago.
Improve this question
I had a beginning question to read in a two digit number and give it back splittet into its numbers but I soon saw, that the code I created was not really handy, when wrong inputs where done.
So I did a research about if-statemants, .length feature, regex method and comperative operators. What came back was my rudimental first script for input a two digit number, prove if it is 2 digits long, prove if it is a number and give it back. Now I have some questions to You specialists (it is a console application btw.):
Was it the right way to use regex with the IsMatch method, or would be another method saver and cleaner (maybe also another variant of regex)
Is it possible to shorten the code, Iam not so far atm, maybe there are classes or objects to use, to make the code clearer.
Was it the right way to use conditional "and" instead of regular "and", in the if statements?
Are the if statements possible to be shorten, I read about conditional expressions, but I was not sure how far I could nest them (my reference: https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/operators/conditional-operator). Maybe some of You can give me an example on my script.
Is the new operator on regex the right way to implement it, or is there another way to implement regex?
The script works, but maybe there are better and handier solutions.
using System;
using System.Text.RegularExpressions;
namespace TwoDigitSplit
{
class FromTrexToRegex
{
static void Main(string[] args)
{
int digit, digit1, digit2;
string entry;
// Search for one or more decimal numbers with Regex
Regex regex = new Regex("[0-9]+");
// Read in a two-digit number
Console.WriteLine("Enter a two-digit number:");
entry = Console.ReadLine();
// Check for length longer than two-digit and also check if it is numbers
if (entry.Length>2 && regex.IsMatch(entry))
{
Console.WriteLine("The number is longer than two-digit, please try again!");
}
// Check for length smaller than two-digit and also check if it is numbers
else if (entry.Length<2 && regex.IsMatch(entry))
{
Console.WriteLine("The number is shorter than two-digit, please try again!");
}
// Check for integer numbers and if the number is between 10 inklusiv and 100 exklusiv
else if(Int32.TryParse(entry, out digit) && digit >= 10 && digit <100)
{
// Evaluate the number and write it
digit1= digit / 10;
digit2 = digit % 10;
Console.WriteLine("The number has on the first place {0} and on the second place {1}", digit1, digit2);
}
// If no number has been plottet
else
{
Console.WriteLine("You did not enter a number!");
}
}
}
}
There are no error results atm. I could see, I only had some questions about the methods, classes and operators.
Answers
regex = new Regex(...) ... regex.IsMatch(...) is possible, but I suggest static Regex.IsMatch as more readable here
Yes, some conditions are redundant
I suggest separated regex condition (testing for value) and length (testing for length)
Ternary operator ? : must return a value, in you case you want to call a method - Console.WriteLine; stick to if
regex = new Regex(...) is possible, but I don't think it's good in the context. You want to test just once: Regex.IsMatch(...) is more readable
Code:
Console.WriteLine("Enter a two-digit number:");
// Trim: let us be nice and tolerate leading and trailing spaces
// (esp. in case user put it with copy-pasting)
entry = Console.ReadLine().Trim();
// Just check the length
if (entry.Length > 2)
{
Console.WriteLine("The number is longer than two-digit, please try again!");
}
// Check for length smaller than two-digit
else if (entry.Length < 2)
{
Console.WriteLine("The number is shorter than two-digit, please try again!");
}
// The length is correct, time to check the value
else if (!Regex.IsMatch(entry, "^[0-9]{2}$")) // <- just a static method
{
Console.WriteLine("The input is not 2 digit number, please try again!")
}
// The entry is valid, let's ptint the result out
else
{
// You don't have to parse and do arithmetic
// if you want to convert char to corresponding digit: '7' -> 7
int digit1 = entry[0] - '0';
int digit2 = entry[1] - '0';
// String interpolation is often more readable than formatting
Console.WriteLine(
$"The number has on the first place {digit1} and on the second place {digit2}");
}

C# increment a variable and convert to string on one line [duplicate]

This question already has answers here:
Pre- & Post Increment in C#
(6 answers)
Closed 5 years ago.
Simple request -- does anybody know a way to consolidate this to one line:
edit - I was NOT confused about pre vs post increment operators. The question I posted should have worked, I honestly do not know what happened. somewhere between VS and SO I fixed it.
startingMask++;
string mask2 = startingMask.ToString().PadLeft(3, '0');
Something like
string mask2 = (startingMask++).ToString().PadLeft(3, '0');
edit -- Alright -- chill out -- :)
Here is the final full solution, I should have provided more info in my first question, I was just looking for a nudge in the right direction (the number needed and starting number will be changing via a database pull at some point):
int startingMask = 76;
int numberNumberNeeded = 10;
List<string> masks = new List<string>();
while (numberNumberNeeded > 0)
{
string newMask = (startingMask++).ToString().PadLeft(3, '0');
masks.Add(newMask);
numberNumberNeeded--;
}
string mask2 = (++startingMask).ToString().PadLeft(3, '0');
Postfix ++ startingMask++ first take value and then increment value
Sufix ++ ++startingMask first increment value and then take value

How to convert int to List<int> [closed]

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 6 years ago.
Improve this question
I want an solution to convert an input int say 010 to list of int {0,1,0}.
Below is code I tried, works until 0 is encountered.
Int num = 010;
List<int> listOfInt = new List<int>();
While(num > 0)
listOfInt.Add(num%10);
num / = 10;
I just want to split entered int and convert it to list of int. LINQ is fine if that could be efficient!
As others already mentioned 010 is identical to 10 when having parsed as int. However you could have your number as string coming from a console-input for example.
string myNumber = "010";
This can be split on every character quite easy using LINQ:
var intList = myNumber.Select(x => Convert.ToInt32(x.ToString())).ToList();
As every character is internally an int where '0' equals 49 you have to convert every single character to a string before which is done by using ToString.
Console.WriteLine("Enter a number:")
var input = Console.ReadLine();
List<int> result = input.Select(c => int.Parse(c.ToString())).ToList();
There is no difference between 010 and 10 either in computer arithmetic or real life. Zero is zero.
If you want to convert the number to a specific string format and extract the characters, perform the same steps as the statement:
10.ToString("000").Select(c=>c-48).ToList();
The result is a list with the numbers 0,1,0.
The expression c-48 takes advantage of the fact that characters are essentially ints, and digits start from 0 upwards. So 48 is 0, 1 is 49 etc.
If the input is a string, eg "10" you'll have to pad it with 0s up to the desired length:
"10".PadLeft(3,'0').Select(c=>c-48).ToList()
The result will be 0,1,0 again.
If, after all, you only want to retrieve characters from a paddes string, you only need padding, as a String is an IEnumerable. You can copy the characters to an array with String.ToCharArray() or to a List as before:
"10".PadLeft(3,'0').ToList()
string num = "010";
List<int> listOfInt = new List<int>();
foreach(char item in num)
{
listOfInt.Add(Convert.ToInt32(item.ToString()));
}

Getting a substring 2 characters at a time [duplicate]

This question already has answers here:
Splitting a string / number every Nth Character / Number?
(17 answers)
Closed 8 years ago.
I have a string that looks something like:
0122031203
I want to be able to parse it and add the following into a list:
01
22
03
12
03
So, I need to get each 2 characters and extract them.
I tried this:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i=i+2) {
mList.Add(_CAUSE.Substring(i, _CAUSE.Length));
}
return mList;
but something is not right here, I keep getting the following:
Index and length must refer to a location within the string. Parameter
name: length
Did I get this wrong?
How about using Linq?
string s = "0122031203";
int i = 0;
var mList = s.GroupBy(_ => i++ / 2).Select(g => String.Join("", g)).ToList();
I believe you have may have specified the length incorrectly in the Substring function.
Try the following:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i = i + 2)
{
mList.Add(_CAUSE.Substring(i, 2));
}
return mList;
The length should be 2 if you wish to split this into chunks of 2 characters each.
when you do the substring, try _CAUSE.SubString(i, 2).
2points:
1) as previously mentioned, it should be substring(i,2);
2) U should consider the case when the length of ur string is odd. For example 01234: do u want it 01 23 and u'll discard the 4 or do u want it to be 01 23 4 ??

Format number as ranking position [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is there an easy way in .NET to get “st”, “nd”, “rd” and “th” endings for numbers?
Is there anything already built into C# that formats a number as a ranking position?
By "ranking position" is mean one of ["st","nd,"rd","th"] eg : (1st, 2nd, 3rd, 4th).
I know it'd be easy to write an extension for this, I'm just wondering if there is already something in the language to cater.
Cheers
No, there is nothing built-in for this purpose. Not sure if its relevant, but consider cultural differences if you span languages/cultures.
I've been corrected. Please see the duplicate questions as described in the comments above.
Not out-of-the-box; however, as you mentioned, an extension is pretty easy.
public static string ConvertToRankingPosition(this int value)
{
var digit = value % 10;
return value != 11 && digit == 1 : value + "st" :
value != 12 && digit == 2 : value + "nd" :
value != 13 && digit == 3 : value + "rd" :
value + "th"
}

Categories