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]))?$"
Related
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...
My application seem crash on "wrong format", I have this:
Match m = Regex.Match(value, "[0-9]+[.[0-9]+]?");
double number = Convert.ToDouble(m.Value);
return number;
Point is to make string values like this: 114.6W, 120.6W. into values I can sort.
My function that I wrote is suppose to turn any string into a 9999.9999 double value, but it crash on Convert.ToDouble(). Saying wrong input format?
Maybe the . is not the decimal separator for the culture you are using. Try specifying InvariantCulture when parsing:
double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
The problem is with your regex: it should read
[0-9]+(\.[0-9]+)?
[.[0.9]+] (which I am surprised parses at all) is a character class looking for any character in the following set: a dot, an opening and closing bracket, 0 to 9, or a plus sign.
You must replace square brackets by parenthesis
Match m = Regex.Match(value, #"[0-9]+(?:\.[0-9]+)?");
If it is guaranteed to always be a decimal number followed by a single letter, then:
var word = "120.6W";
var d = Decimal.Parse(word.Substring(0,word.Length-1));
Try these two regexes, you may need to test and adjust to your needs
this one will grab all numbers including the ., but only if followed by a W (won't grab the w)
(?i)\d+\.\d+(?=w)
this one will grab all the digits regardless what's after it
\d+\.\d+
or if your data sets consists of only the numbers plus one letter and nothing in front or after it, do as #paul suggests, just strip the last char
I am not good with regular expression patterns.
I have to put a validation on an string, to allow
only alphabets, numbers, decimals, spaces, comma and underscore
for allowing the alphabets and spaces I have /^[a-zA-Z][a-zA-Z\\s]+$/
Please help me in creating all the above conditions in one pattern.
Thanks
this regex should work for your requirements
'[a-zA-Z0-9_. ,]*'
In the regex, I specified the range a to z, A to Z (uppercase), 0 to 9 and the single character _, decimal point ".", space and a comma.
If you want to make sure you want at least one character after the first letter, you can replace the * with a +, or {2,} with at least 2 more characters, or {2,5} with between 2 and 5 characters.
You can try:
/^[\w., ]+$/
I don't know what are the requirements for the starting char, if there are any.
Rahul's answer gave me the direction to think, but for the visitors, may be this too can be helpfull
patternForClasName = /^([a-zA-Z0-9 _]+\.)*[a-zA-Z0-9 _]+$/;
// Allowing valid className which has a format abcsasa.dsd.dsd(the class or a package name can have an underscore or a numerical)
patternForName = /^([a-zA-Z0-9 _-]+)$/;
// Allowing alphanumeric + spaces + (_)underscore and a (-)dash
patternForDescription = /^([a-zA-Z0-9 _-]+[\,\.]+)*[a-zA-Z0-9 _-]*$/;
// Allowing alphanumeric,spaces, (_)underscore, (-)dash, comma, decimal
patternURLFormat = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
// For a valid URL
Is it possible to create a 'dynamic' discount mask that takes % or numbers as discount values? What is the simple way to do this?
the samples of valide input: -25% or 0.25 or -5$ not 0 and two digit after dot
Try
#"(\+|-)?(\d+(\.\d*)?|\.\d+)%?"
It will find:
123.23
12.4%
.34
.34%
45.
45.%
8
7%
34
34%
+2.55%
-1.75%
UPDATE
and with ...
#"(\+|-)?(\d+(,\d{3})*(?!\d)(\.\d*)?|\.\d+)%?"
... you can include thousands separators as well.
I must confess that my second regex expression looks like a cat had walked accross my keyboard. Here the explanation
(\+|-)? optionally ? a plus or a minus sign.
\d+(,\d{3})*(?!\d)(\.\d*)? one or more digits \d+ followed by any number of thousands separators plus three digits (,\d{3})*, not followed by any digit (?!\d) in order to disallow four digits in sequence, optionally followed by a decimal point and any number of digits (\.\d*)?.
|\.\d+ or alternatively a decimal point followed by at least one digit.
%? finally an optional percent sign.
If I understand your question right, you want something like this:
#"^[+-]?(?:\d*\.)?\d+[%$]?$"
That's partly based on your example of -5$. Usually, though, the $ would go in front, so you'd want something like:
#"^(?:\$(?!.*%))?[+-]?(?:\d*\.)?\d+%?$"
That would allow $-5.00, 10, or +20%, but block $5%.
Edit:
Running with Olivier's idea of allowing commas:
#"^(\$(?!.*%))?[+-]?(\d{1,3}((,\d{3})*|\d*))?(\.\d+)?\b%?$"
Expanded to make it easier to understand:
#"^ #Require matching from the beginning of the line
(\$(?!.*%))? #Optionally allow a $ here, but only if there's no % later on.
[+-]? #Optionally allow + or - at the beginning
(
\d{1,3} #Covers the first three numerals
((,\d{3})*|\d*) #Allow numbers in 1,234,567 format, or simply a long string of numerals with no commas
)? #Allow for a decimal with no leading digits
(\.\d+)? #Optionally allow a period, but only with numerals behind it
\b #Word break (a sneaky way to require at least one numeral before this position, thus preventing an empty string)
%? #Optionally allow %
$" #End of line
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+$