Regex c# only positive numbers - c#

I am looking for a regular expression that validates only positive numbers(integers):
0-999 and first number not 0.
My example not work:
string pattern = #"^\d+$";
How decided positive numbers pattern?

You could force the first digit to be 1-9, and then have any or no digits follow it, like so;
string pattern = #"^[1-9]\d*$";
You can also restrict the amount of digits by putting a numbered constraint on it.
string pattern = #"^[1-9]\d{0,2}$";
The top one will accept any positive integer >0, while the bottom one will accept only 1-999.

How about
#"^[1-9]\d?\d?$"
1-9 followed by 2 optional digits?

use this regular expression ^[1-9]\d{0,2}$

If you just want to validate an input, why not using TryParse?
Regular Expression for positive numbers in C#
double result = 0;
if (Double.TryParse(myString, out result))
{
// Your conditions
if (result > 0 && result < 1000)
{
// Your number
}
}

You can use a lot of useful regex tools online like http://gskinner.com/RegExr/
there's a lot of ready to use examples from which you can start to get your own!

The positive number with two digits after comma:
\d*\,\d\d

Related

How to validate a number with preceding zeros with regex [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 7 years ago.
I have the following rule:
Don't allow numbers of any sequence with 4 or more 0s at the beginning.
So this number:
0000438967
will fail validation (4 zeros)
But this number:
0004389678 (3 zeros)
Will pass validation.
the reason for this question was I needed verification on whether I was doing it correctly as, when checking in online Regex validators, I was getting mixed verification results. I know it sounds like a simple question but verification from others is important.
thanks
Russ
Unbelievable amount of trial & error answers on this question! The solution is as simple as this:
string number = "0000438967";
bool pass = Regex.IsMatch(number, #"^0{0,3}[1-9]\d*$");
This allows numbers of any length, as long as there is at least one non-zero digit. Replace the last asterisk by {n} or {m,n} to also check length.
Of course, you may want to construct a Regex instance for repeated use.
If you also need the numeric value, you can immediately parse it if pass == true:
int value = Int32.Parse(number);
Of course, depending on the maximum length you want to allow you might need an Int64... but anyway you must provide a maximum length in the regex or the Parse can cause an overflow.
If you must use regular expression, you can use a Negative Lookahead assertion.
^(?!0000)\d+$
Lookarounds are zero-width assertions. They don't consume any characters on the string. The point of zero-width is the validation to see if a regex can or cannot be matched looking ahead or looking back from the current position, without adding them to the overall match.
Example:
Regex.IsMatch("0438967", #"^(?!0000)\d+$"); // True
Regex.IsMatch("004389678", #"^(?!0000)\d+$"); // True
Regex.IsMatch("000438967", #"^(?!0000)\d+$"); // True
Regex.IsMatch("00004389678", #"^(?!0000)\d+$"); // False
Regex.IsMatch("00000438967", #"^(?!0000)\d+$"); // False
Regex.IsMatch("000000438967", #"^(?!0000)\d+$"); // False
Zero to three zeroes followed optionally by a nonzero number followed by any number of numbers:
0{0,3}([1-9][0-9]*)?
It should accept:
000
While rejecting any number with 4+ zeroes at the beginning.
Don't use a lookahead/behind for this as that triggers backtracking.
EDIT: if your matching function does not perform an exact match then you'll need to do:
^0{0,3}([1-9][0-9]*)?$
Please try this..
string myString = "00011111";//Valid
if (Regex.IsMatch(myString, #"^[0-9]{3}[1-9]+$"))
{
Console.WriteLine("Valid");
Console.ReadKey();
}
Assuming you accept no zeros at all and at least one non-zero digit, here is your regex:
string str = "001";
bool passed = Regex.IsMatch(str, #"^0{0,3}[1-9]\d*$");
Explanation: Regex check for 0 to 3 '0's, then for one non-'0' digits and then for zero or more of any digits.
if "000" is acceptable, then negative look-ahead solution from #hwnd is more elegant. I would just use 0{4} instead of 0000.
You can use Regex to find out the string is valid or not
!Regex.Match(str, #"^0000(\d+)", RegexOptions.IgnoreCase).Success
here is working sample rextester

Regular expression only one character and 7 numbers

i want regex match only one char in any position of word and 7 numbers
match example:
1111111q
2222222q
111e1111
11e11111
i do this pattern but not working in all patterns:
[A-Za-z][0-9]{7}
Regular expressions match patterns. In your case, it would seem that the letter can be at any point in your string, which would mean that you would have a multitude of patterns which would need to be taken into consideration.
I think that for this case, you should not use regular expressions for simplicity's sake. I would recommend you take a look at the Char.isDigit(Char c) and Char.isLetter(Char c) methods and use counters to see that the string is in the format you are after.
there are readily available methods in C# for checking the conditions you want. I would use Regex if there is no parser or simple c# solution.
I would do like below
var str = "1111111u";
var isValid = str.Length ==8 &&
str.Where(char.IsDigit).Count() ==7 &&
str.Where(char.IsLetter).Count() ==1;
It is not that difficult in regex:
If the complete string has to match just use:
^(?=.{8}$)\d*[a-zA-Z]\d*$
See it here on regexr.
If this is a word in a larger text use:
\b(?=[a-z0-9]{8}\b)\d*[a-z]\d*\b
See it here on Regexr
\d*[a-z]\d* matches any amount of digits, followed by one letter, then again any amount of digits.
(?=[a-z0-9]{8} is a positive lookahead assertion, this ensures the length of 8 in total.
Important here is the use of anchors or word boundaries to avoid partial wrong matches.
If you really want to match any letter then use the Unicode property \p{L} instead of the character class:
^(?=.{8}$)\d*\p{L}\d*$
I can only come up with a "brute force" regex method:
foundMatch = Regex.IsMatch(subjectString,
#"\b
(?:[a-z]\d{7}|
\d[a-z]\d{6}|
\d{2}[a-z]\d{5}|
\d{3}[a-z]\d{4}|
\d{4}[a-z]\d{3}|
\d{5}[a-z]\d{2}|
\d{6}[a-z]\d{1}|
\d{7}[a-z])
\b",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
Note the word boundary anchors, which you should remove if this pattern is part of a longer string.
Also note the IgnoreCase option, which you can remove if all letters will be lower case.
Edit: See #stema Answer -- much more concise regex
This will match what you want:
(\d{1}\w\d{6}|\d{2}\w\d{5}|\d{3}\w\d{4}|\d{4}\w\d{3}|\d{5}\w\d{2}|\d{6}\w\d{1}|\d{7}\w)
I generated it like this, in powershell:
$n = 6;
for ($i = 1; $i -le 6; $i++) {
write-host "\d{"$i"}\w\d{"$n"}"
$n--
}
Your example will only work when the character is the first character in the string.
The problem you've got is that you need a total of 7 digits, and absolutely only one character potentially within those 7 digits. This is not something that's possible with regular expressions as defined in theory, because you have to have a link between the two groups of digits to see how many are in the other group and regexes can't carry that kind of context around with them.
I was wondering if it was possible using a lookahead assertion to ensure there's only one letter, but the best I can do is ensuring there's no instance of two letters in a row, which doesn't cover all possible invalid cases. Thus I think you're going to have to find another method, as npinti suggested. So something like:
public static bool Match(string s) {
return (s.Length == 8) &&
(s.Where(Char.IsDigit).Count() == 7) &&
(s.Where(Char.IsLetter).Count() == 1);
}
But I haven't tested that.
just use this if you want one letter and 7 digit
"[A-Za-z]{1}[0-9]{7}|[0-9]{7}[A-Za-z]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{6}[0-9]{1}|[0-9]{2}[A-Za-z]{1}[0-9]{5}|[0-9]{3}[A-Za-z]{1}[0-9]{4}|[0-9]{4}[A-Za-z]{1}[0-9]{3}|[0-9]{5}[A-Za-z]{1}[0-9]{2}"
and here a code snippet how you can iterate through your result
string st = "1111111q 2222222q 111e1111 11e11111";
string pattS = #"[A-Za-z]{1}[0-9]{7}|[0-9]{7}[A-Za-z]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{6}[0-9]{1}|[0-9]{2}[A-Za-z]{1}[0-9]{5}|[0-9]{3}[A-Za-z]{1}[0-9]{4}|[0-9]{4}[A-Za-z]{1}[0-9]{3}|[0-9]{5}[A-Za-z]{1}[0-9]{2}";
Regex regex = new Regex(pattS);
var res = regex.Matches(st);
foreach (var re in res)
{
}
check here on rubular it covers all examples you provide
You can use this pattern:
^([0-9])(?:\1|[a-z](?!.*[a-z])){7}|[a-z]([0-9])\2{6}$
With Regex, you can do it in two steps. First you can remove the character, in whatever position it is:
string input = "111a1111";
Regex rgx = new Regex(#"[a-zA-Z]");
string output=rgx.Replace(input,"",1); // remove only one character
// output = "1111111"
then you can match with [0-9]{7} (if you don't want all digits to be the same)
or with ^(\d)\1{6}$ (if you want 7 occurrences of the same digit)

Regular Expression for Integer greater than 0 and less than 11

I am trying to modify this Regex so that you get numbers greater or equals 1 or less than or equals to 10. This Regex allows >= 0 or <= 10.
I have a text field on a form that takes numbers equals or greater than 0 and less than 11. I could use IF's and logical operators, TryParse but I kinda like the Regex.
#"^\d$|^[1][0]$"
You need to modify your regex only a little bit
#"^[1-9]$|^10$"
You don't need the square brackets around single characters and I would use a group around the alternation and change it to
#"^([1-9]|10)$"
See it here on Regexr
The answer is this is not something for which you should use regex. If anything you would use regular expressions to parse out the numbers and then compare them with standard if (num >= 0) etc.
// EDIT: replaced regex with this:
int number;
if (Int32.TryParse(myString, out number)) {
// do something, like:
if (number >= 0 || number <= 10) {
}
}
If you are using WinForms, then NumericUpDown control with MinValue equal to 1 and MaxValue equal to 10 will do the job. Also you don't need parsing - property Value will contain your value (well, it will be of type decimal - just cast it to int).
Another reason for using NumericUpDown - it does not allow to input anything except digits, and up-down arrows are saying to user - this control is waiting numbers from you.
While I recommend simply using logical operators to check if an int is between 1 and 10, here's a working regex:
^(10|[1-9])$
Here you are:
^(1|2|3|4|5|6|7|8|9|10)$
Very explicit, can't misinterpret, clear as day. Makes for a better regex for me. Short and cryptic isn't necessary here
you can try this:
^([1-9]|10)$
Use Regex to check number from 1 to 10 -
^([1-9]|10)$

Regular Expression for positive numbers in C#

I am looking for a regular expression that validates only positive numbers.
e.g.
0 is invalid.
0.123 is valid.
any positive integer is valid.
any negative number is invalid
If you are simply trying to validate input numbers as valid positive numbers, you don't need Regex - simply use the Parse or TryParse methods defined on Double or Decimal and check for the value being positive.
decimal test;
if(decimal.TryParse(myString, out test))
{
// parsed OK, myString is a valid decimal
if(test > 0)
{
// yay, it is positive!
}
}
I'm not convinced that a regex is the best way to test for positive numbers, but if you must use a regex for some reason then this should meet your stated requirements:
^(?:[1-9]\d*(?:\.\d+)?|0\.0*[1-9]\d*)$
Try this
^(?!-|0(?:\.0*)?$)\d+(?:\.\d+)?$
See it here on Regexr
^ the start of the string
(?!-|0(?:\.0*)?$) negative lookahead assertion, fails when the string starts with "-" or a 0 and 0.0* followed by the end of the string.
\d+ matches at least one digit
(?:\.\d+)? matches optionally a dot followed by at least one digit
$ the end of the string
this can help u
Positive Number --- ^\d*\.{0,1}\d+$

Regular expression for 10 digit number without any special characters

What is the regular expression for a 10 digit numeric number (no special characters and no decimal).
Use this regular expression to match ten digits only:
#"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
#"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:
#"(?<!\d)\d{10}(?!\d)"
Use the following pattern.
^\d{10}$
This works for me:
only 10 digit number is accepted.
^[0-9]{10}$
\d{10}
I believe that should do it
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(#"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
Use this:
\d{10}
I hope it helps.

Categories