Regular Expression for positive numbers in C# - 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+$

Related

Regex floating point Number Formatter for Wpf Textbox

I saw Regex today for the first time. I need a regex formatter for my WPF Textbox like this:
12345,1234
I need a decimal separator like "," or "." and negative Numbers should be allowed.
So you can write something like this:
230,56 / 1289,4 / -1.9 / 63478,1252 / 0.3265
This should not be possible:
086,344 / 34,7000 / 1.0×10−4
A 0 at first if there is not a comma behind there should not be allowed. And if the last Number after the Comma is a 0 is also bad. No scientific notation.
I found a code for simple integer values:
private void Int_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
// Just Ints
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
So how does a formatter for floating point numbers like my description looks like?
Looking at your requirements, it seems that the following pattern would work:
^-?(?!.*0$)(?!0\d)\d+(?:[,.]\d+)?$
See the demo
^ - Start string ancor.
-? - Optional hyphen to allow for negative values.
(?!.*0) - Negative lookahead to prevent a string that ends with 0.
(?!0\d) - Negative lookahead to prevent a string that starts with 0 and a digit.
\d+ - Any digit at least once.
(?: - Open non-capture group.
[,.] - A comma or dot as decimal delimiter.
\d+ - One or more digits.
)? - Close non-capture group and make it optional.
$ - End string ancor.
If you want to check if user entered valid decimal number, .NET offers you readable and simple way of validating that. Justs use decimal.TryParse
In the spirit of "use the right tool for the job", you should not use regex for such validation.
Just use it like:
var parseOk = decimal.TryParse(textBlock.Text, out _); // here I used _ as parameter name, as it is not relevant
if(! parseOk)
{
// validation failed
}
In order to control how decimal separators are treated, you can use overload fo metnioned method:
public static bool TryParse (string s, System.Globalization.NumberStyles style,
IFormatProvider provider, out decimal result);
And please look at the docs.
Also, you have to decide how number will be stored (float, decimal or double). Fortunately, each of these types exposes two static methods: Parse and TryParse - I encourage you to read about them.
I interpret your requirements as follows:
The string might have an optional "-" character in front
Before the decimal separator, there should be either a single "0", or any number of digits not starting with a "0".
After the decimal separator, there should be either a single "0", or any number of digits not ending with a "0".
This translates straightforward to the following regex:
#"^-?(0|[1-9]\d*)[,\.](0|\d*[1-9])$"
If numbers without decimal separators are allowed (the question is not clear about this), the part starting from the separator would be optional, i.e.
#"^-?(0|[1-9]\d*)([,\.](0|\d*[1-9]))?$"

Regular expression in C# for Number with Decimal Point & Commas

I need to enter amount in a textbox which allows numbers with decimal point and commas.
What is the regular expression for this?
I used the below
txtInitialAmountGuarDetails.ValidationSettings.RegularExpression.ValidationExpression
= #"^[-+]?\d*[0-9](|.\d*[0-9])(|,\d*[0-9])?$";
But it not working for large numbers like 300,000,000,000,000.
Build it up piecemeal. Given a US locale, a number with these rules has in order:
The string beginning: ^
An optional sign: [+-]?
Up to 3 digits: \d{1,3}
A comma followed by 3 digits, repeated any number of times: (?:,\d{3})*
An optional decimal point and decimal part: (?:[.]\d+)?
The string end: $
Do you have restrictions on the number of digits after the decimal point? Then change the last plus sign to {2} for 2 digits.
So, the regex is:
#"^[+-]?\d{1,3}(?:,\d{3})*(?:[.]\d+)?$"
Or, if you want to explain your work, use the x option and:
#"(?x) # Extended format.
^[+-]? # Optional sign.
\d{1,3} # Initial 1-3 digits.
(?:,\d{3})* # Any number of commas followed by 3 digits.
(?:[.]\d+)?$" # An optional decimal point followed by any number of digits.
But does C# have a locale-dependent validator already?
I have not run it, but you can try it out.
var regexp =/^\s*?([\d\,]+(\.\d{1,2})?|\.\d{1,2})\s*$/;
This works: \d{1,3}(,\d{3})*\.{0,1}(\d{3},)*\d{0,3}
As for the after the comma issue, any choice should be fine. If you go with commas, my regex works. If you do 5 digits then a space just replace the end with (\d{5}\s{1})*\d{0,5}. And ofcourse if you just dont use any deliminator after the decimal you just put \d*
You can try this regex too:
^([+-]?\d{1,3}(?:,\d{1,3})*(?:\.\d+)*)$
Keep in mind . has a specific meaning in regex engine so it is necessary to escape it.
I would also suggest you to not use regex for this task instead look at masked textbox.
try this one:
^([0-9]{3}[,.]|)+[0-9]{0,3}$
let me know if it needs any enhancements...

Regex c# only positive numbers

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

How can I use a Regular Expression to return a number of numbers at the end of a string of digits

I have a string of digits that could vary in length and I want to return only the last 4 digits. Would I use a positive lookback? And use the $ to anchor to?
use this regular expression \d{4}$
If your string can be ANY length and you want to match the cases when you have 0 to 3 charaters you should use:
\d?\d?\d?\d?$
or, if the regex engine understands it:
\d{0-4}$

C# RegEx for decimal number or zero (0)

This gets all numbers but not floating numbers
Regex(#"^\d+$")
I need it to get these values as well:
1234.12345545
0
12313
12313.13
-12131
-1313.13211312
For matching all of the above; the most appropriate regex is probably
#"^[+-]?\d+(\.\d+)?$"
This matches all of the above; but not numbers on the format .3456.
It also matches numbers on the format +123 and -1234.5678
Try this here
^(?:[-+]?[1-9]\d*|0)?(?:\.\d+)?$
This will additionally match the empty string.
See it online here on Regexr
If matching the empty string is not wanted, then you can add a length check to your regex like
^(?=.+)(?:[-+]?[1-9]\d*|0)?(?:\.\d+)?$
The positive lookahead (?=.+) ensures that there is at least 1 character

Categories