Decimal and only positive numeric values - c#

What regex i can use for positive numeric and decimal values ?
Accepted values: 0, 22.5 , 0.35 , 89 , .38
Invalid values : -22 , -.25 , -0.66 , abc, -22abc, 55er
I have tried this but i get error
^\d*\.?\d*[1-9]+\d*$)|(^[1-9]+\d*\.\d*$"
Too many )'s
^\d*\.?\d*[1-9]+\d*$)|(^[1-9]+\d*\.\d*$

You're missing a closing ) in the regex.
^\d*\.?\d*[1-9]+\d*$)|(^[1-9]+\d*\.\d*)$
However, I'd strongly suggest you look at Decimal.TryParse instead of trying to validate numbers using the format of a string yourself.

I would simply your pattern to this:
\d*(?:\.\d+)?
Demo
This seems to cover all your positive decimal number use cases. The decimal component is optional, meaning that the pattern covers integers. Decimal numbers are covered, and also numbers which only have a decimal component.
Note that you might have to surround the pattern with ^$ anchors, depending on the particular API you are using.
Edit:
If you also need to ensure that empty string is not matched, then we can add a lookahead to the above pattern:
(?=.)\d*(?:\.\d+)?
Demo

Or, if you want to stay away from Regex, one of these might work:
private static bool IsPositiveDecimal(string decimalString)
{
return decimal.TryParse(decimalString, out var aDecimal) && aDecimal >= 0;
}
or
private static bool TryParsePositiveDecimal(string decimalString, out decimal aDecimal)
{
return decimal.TryParse(decimalString, out aDecimal) && aDecimal >= 0;
}
If you feed the latter one a non-positive decimal, it will return false, but will return the parsed decimal in the out parameter.
This should suit your needs without injecting a complicated Regex into your code.

I believe this regex should meet all the cases and will only match valid samples and discard all invalid ones.
^(?:[1-9]\d*(\.\d+)?|0?\.\d+|0)$
Regex Explanation:
^ - Start of string
(?: - Start of non capture group
[1-9]\d* - Matches a number without unneeded preceding zeroes. Will invalidated 01 or 001
(\.\d+)? - Can optionally have decimal part
| - Alternation
0?\.\d+ - Allows only decimal numbers that can optionally have zero before them. E.g. to support numbers like 0.11 or .11
| - Alternation
0 - Supporting literal zero as a special case
) - closing of non-capture group
$ - End of string
Demo

^\d*\.?\d+$
There will also match 0.00 .00 0.0

Related

Regular Expressions C#

I know there are many questions about making regular expressions, but they all seem to be about a single problem than the general usage. I, too, have a problem like to solve. I have tried to learn by reading about regular expressions, but it gets tricky quick. Here's my question:
C#
I need to validate two textboxes that exist on the same form. The math operations I've coded can handle any floating point number. For this particular application I know of three formats the numbers will be in or there is a mistake on the users behalf. I'd like to prevent those mistakes in example if an extra number is accidentally typed or if enter is hit too early, etc.
Here are the formats: "#.####" "##.####" "###.##" where the "#" represents a mandatory digit. The formats starting with a one or two digit whole number must have 4 trailing digits or more. I've capped it at 8, or so I tried to lol.The format starting with a three digit whole number should never be allowed to have more than two digits trailing the decimal.
Here's what I have tried thus far.
Regex acceptedInputRegex = new Regex(#"^\b[0-9]{3}.[0-9]{2}|[0-9]{1,2}.[0-9]{4,8}$");
Regex acceptedInputRegex = new Regex(#"^\b\d{3}.\d{2} | \d{1,2}.\d{4,8}$");
I have tried it in thinking a match was what I wanted to achieve and as if a match to my negated expression means there is a problem. I was unsuccessful in both attempts. This is the code:
if (acceptedInputRegex.IsMatch(txtMyTextBox1.Text) || acceptedInputRegex.IsMatch(txtMyTextBox2.Text))
{
} else
{
MessageBox.Show("Numbers are not in the right format", "Invalid Input!");
return;
}
Are regular expressions what I should be using to solve this problem?
If not, please tell me what you recommend. If so, please help me correct my regex.
Thanks.
You are close, you need to escape the dots and group the alternatives so that the ^ and $ anchors could be applied to both of them:
#"^(?:\d{3}\.\d{2}|\d{1,2}\.\d{4,8})$"
See the regex demo.
Details:
^ - start of string
(?: - start of a non-capturing group matching either of the two alternatives:
\d{3}\.\d{2} - 3 digits, . and 2 digits
| - or
\d{1,2}\.\d{4,8} - 1 or 2 digits, ., 4 to 8 digits
) - end of the non-capturing group
$ - end of string.
To make \d match only ASCII digits, use RegexOptions.ECMAScript option:
var isValid = Regex.IsMatch(s, #"^(?:\d{3}\.\d{2}|\d{1,2}\.\d{4,8})$", RegexOptions.ECMAScript);

How to give regular expression for Regex.ismatch function?

I am trying to write a regular expression for accepting a Number of length upto 14 and if they keep the decimal point then it should accept only 2 numbers after the decimal point.
I have tried it from this link below :
https://stackoverflow.com/a/9967694/861995
But, the same Regex.IsMatch function is not accepting the normal regex expression's starting with ^ and ending with $.
Please help me on this i am new to regular expressions
private void ChangedSellUp_KeyDown(object sender, KeyEventArgs e)
{
string pattern = "^[0-9]*$";
Regex rx = new Regex(pattern);
if (rx.IsMatch(ChangedSellUp.Text))
{
e.Handled = true;
}
}
Here ChangedSellup.Text is my text box value, i am trying to restrict the value based on 2 conditions
Its Should Accept only Numbers and length should not increase 14 till Decimal Point.
If decimal Point is there after that only 2 numbers are allowed.
e.g ; valid Values - 14.23, 12345678901234.23
Invalid values - 1.2344, 12345678901234.3455
Please help me with the regex ??
The best way to build regular expressions is with a Regex Tester. There's a really good one you can download called Cappucino, or you can use a web one, I favour http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
Then it is simply a case of building the regex, I'm testing against 12345678901234.00
If you start with \d which is the regex pattern for a numeric digit then you get all sixteen matches you would expect.
Add a + which is short for one or more, so \d+ matches twice 12345678901234 and 00
If you limit to a range of only two digits i.e. \d{2} then you get 8 pairs of numbers
To add a . you need to escape the character as . is a pattern to match any digit, so instead use \.\d{2} to match only .00 (which was your optional part of the number)
If you pattern match a range of digits between 1 and 14 long \d{1,14} then you will match 12345678901234 (which is the main number) and 00
So now you can put it together, we make the post decimal point part optional by saying we want it either 0 or 1 times {0,1} or with a shorthand variant ? to give
\d{1,14}(\.\d{2})?
which matches correctly on these
12345678901234.00
123456.00
1
1234
and because I'm not matching the start and end of the line, also matches on these
500.00USD
$1000
Here's the Regex.IsMatch that does what you want:
Regex.IsMatch("12345678901234.12", #"^\d{1,14}(?:\.\d{1,2}){0,1}$")
That particular regex is for a number up to 14 digits before the decimal point and 1 or 2 digits after the decimal point (with the whole decimal part being optional)
A good place to test it is here: http://regexhero.net/tester/
Because you've mentioned ^ and $, I've included them in the regex, which will only parse lines with just the number (so, for example " 1234.12 " won't return true in the IsMatch, just remove the "^" and "$" if that is not important).
Another good resource for regex is this: http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
UPDATE:
Since the goal is that the user cannot write anything other than something that satisfies that Regex in a textbox you can do this in the text changed event (key down is not a good option since you'd have to deal with converting KeyEventArg's Key to a char). So the easiest way to achieve what you need is:
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (!Regex.IsMatch(TextBox1.Text, #"^\d{1,14}(?:\.\d{0,2}){0,1}$"))
{
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - e.Changes.Last().AddedLength);
TextBox1.CaretIndex = TextBox1.Text.Length;
}
}
Please notice the slight change in the regular expression that will accept a number followed by a dot, with no extra digits, this is because as you are writing a number with decimal places you'll be in a state where this happens, for example: "123."

Regular expression needed for this pattern: point(latitude,longitude)

I am trying to validate text that follows the pattern below:
Must have the text "point(" at the beginning
Must follow it by a Latitude numerical value with up to 5 decimal places (example: 42.12345)
Must follow it by a comma ","
Must follow it by a Longitude numerical value with up to 5 decimal places (example: -81.12345)
Must follow it by a closing parentheses ")"
Matching example:
point(42.12345,-81.12345)
Any help is greatly appreciated.
Thanks.
You can easily build your regex with a little bit of break-up here.
To match point( at the beginning, use - ^point\(
To match a latitude or longitude numbers, use - [-]?\d+(?:\.\d+)?
And again, to match ) at the end, use \)$.
For [-]?\d+(?:\.\d+)?, here's an explanation: -
[-]? - matches an optional negative (-) sign at the starting (? quantifier at the end means 0 or 1)
\d+ - matches one or more digits
(?:\.\d+)? - matches an optional decimal, followed by one or more
digits. dot(.) is a special meta-character in Regex, so you need to escape it, if you want to match it.
Also, to limit your number of digits to 5, you can use - \d{1,5} instead of \d+, which matches minimum 1 and maximum 5 digits.
^(caret) and $(dollar) anchors matches the beginning and end of the string.
So, here's your regex: -
^point\([-]?\d+(?:\.\d{1,5})?,[-]?\d+(?:\.\d{1,5})?\)$
Try this:
^point\(\-?\d+\.\d{1,5},\-?\d+\.\d{1,5}\)$
Must have the text "point(" at the beginning: ^point\(
Must follow it by a Latitude numerical value with up to 5 decimal places (example: 42.12345): \-?\d+\.\d{1,5}
Must follow it by a comma ",": ,
Must follow it by a Longitude numerical value with up to 5 decimal places (example: -81.12345): \-?\d+\.\d{1,5}
Must follow it by a closing parentheses ")": \)$
The latitude and longitude logic can be further broken up like this.
\-? = match on a negative sign if it exists (must escape with \ because - has special meaning in RegEx)
\d+ = match one or more decimal characters (i.e. 0 through 9)
\. = match the period (. alone has special meaning, must escape it)
\d{1,5} = match one to five decimal characters
Something like this:
point\((?<lat>-?\d+\.\d{1,5}),(?<long>-?\d+\.\d{1,5})\)
Try using a regex tool, like expresso: http://www.ultrapico.com/Expresso.htm
how about:
^point\((\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)\)$

Regular expression to allow numbers between -90.0 and +90.0

What is the regular expression to allow for numbers between -90.0 and +90.0? The numbers in between can be floating or whole numbers.
I don't think you want to use a Regex for this. Use Double.Parse() (or Double.TryParse()) if your data is stored in a string, and then check the resulting value to ensure that it falls within the desired range. For example:
public bool IsInRange(string value)
{
bool isInRange = false;
double parsed = 0;
if (Double.TryParse(value, out parsed))
{
// use >= and <= if you want the range to be from -90.0 to 90.0 inclusive
isInRange = value > -90.0 && value < 90.0;
}
return isInRange;
}
If your value is already a double, then it's even easier -- no parsing required.
Not that you really want to use a Regex here (you should parse it, instead, and do the comparison on a numeric type - such as float, or double). But, you could do this:
-?(\d|([1-8][0-9])(\.\d)?)|(90(\.0)?)
This will match -90.0 to 90.0, inclusive. If you want it to be exclusive, drop the 90.0 clause.
negative (optional):
-?
single digit
OR double digit, 10-89
\d|([1-8][0-9])
PLUS decimal, 0-9 (optional):
(\.\d)?
OR 90
90
PLUS decimal, 0 (optional):
(\.0)?
If you want to support more decimal points, then change the 0-89.9 clause to:
Specific precision (seven, in this case) \d|([1-8][0-9])(\.\d{1,7})?
Infinite precision \d|([1-8][0-9])(\.\d+)?
Escape, if necessary
"Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems."
This is a problem that would be better solved with a check. But, if you want a regex, you can have a regex.
-?0*((90(\.0*)?)|([1-8]?\d(\.\d*)?))
will work, I think. Match an optional '-', followed by any number of zeros, followed by either 90 with any number of zeros, or a number that consists of an optional tens digit between 1 and 8, followed by a ones digit, followed by a optional decimal and decimal places. But you see why using a regex for this is so messy. Check the bounds as a numbers, not a series of numerals.
A straightforward regex for +/- option sign of a 90.0 range with optional float of 1 decimal place would be :
[-+]?90(?:\.0?)?|[-+]?(?:\d|[1-8]\d)(?:\.\d?)?
Expanded
# [-+] 90.0
[-+]? 90
(?: \. 0? )?
|
# [-+] 89.9 to 0.0
# 0.0 to 89.9
[-+]?
(?:
\d
| [1-8] \d
)
(?: \. \d? )?

Regular expression for accepting alphanumeric characters (6-10 chars) .NET, C#

I am building a user registration form using C# with .NET.
I have a requirement to validate user entered password fields.
Validation requirement is as below.
It should be alphanumeric (a-z , A-Z , 0-9)
It should accept 6-10 characters (minimum 6 characters, maximum 10 characters)
With at least 1 alphabet and number (example: stack1over)
I am using a regular expression as below.
^([a-zA-Z0-9]{6,10})$
It satisfies my first 2 conditions.
It fails when I enter only characters or numbers.
Pass it through multiple regexes if you can. It'll be a lot cleaner than those look-ahead monstrosities :-)
^[a-zA-Z0-9]{6,10}$
[a-zA-Z]
[0-9]
Though some might consider it clever, it's not necessary to do everything with a single regex (or even with any regex, sometimes - just witness the people who want a regex to detect numbers between 75 and 4093).
Would you rather see some nice clean code like:
if not checkRegex(str,"^[0-9]+$")
return false
val = string_to_int(str);
return (val >= 75) and (val <= 4093)
or something like:
return checkRegex(str,"^7[5-9]$|^[89][0-9]$|^[1-9][0-9][0-9]$|^[1-3][0-9][0-9][0-9]$|^40[0-8][0-9]$|^409[0-3]$")
I know which one I'd prefer to maintain :-)
Use positive lookahead
^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,10}$
Look arounds are also called zero-width assertions. They are zero-width just like the start and end of line (^, $). The difference is that lookarounds will actually match characters, but then give up the match and only return the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.
The syntax for look around:
(?=REGEX) Positive lookahead
(?!REGEX) Negative lookahead
(?<=REGEX) Positive lookbehind
(?<!REGEX) Negative lookbehind
string r = #"^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{6,10}$";
Regex x = new Regex(r);
var z = x.IsMatch(password);
http://www.regular-expressions.info/refadv.html
http://www.regular-expressions.info/lookaround.html

Categories

Resources