create regex to accept blank/space or decimal value - c#

I want to create regex in c# which return true for value having blank/space/null or decimal value with 2 decimal points.So not to accept other than that.

Although probably not the most efficient, this regular expression should do what you want:
^((\d+[\.]\d{2})|([\.]\d{2})|()|\s*)$
It requires any decimal number to have two decimal places, but it does accept either 0.99 or .99 as an example.
If you want to allow users to enter in 9 or 9.0 or 9.01 (that is, not force the user to enter in two decimal places) you can just modify the above like this:
^((\d+([\.]\d{0,2})*)|([\.]\d{0,2})|()|\s*)$
It is just setting the quantifiers to {0,2} instead of {2}, and making the existence of decimals places optional.

^\s*(?:[+-]?\d*\.\d{2})?\s*$
matches a number with exactly two decimal places, optionally surrounded by whitespace, or the empty/whitespace only string.

use this regular expression ^(\s+)|(([+-])?\d+[,\.]\d{2})|()|(null)$

I would suggest this pattern to handle numbers and empty string scenario.
^[-+]?\d*(\.\d{2})?|\s*$
Reagrding NULL, I have experienced that when we pass null as an input in RegEx it throws ArgumentNullException. So my recommendation is to validate NULL using != operator by matching with null:
if(str != null && RegEx.IsMatch(str,#"^[-+]?\d*(\.\d{2})?|\s*$"))
// valid data
where:
str = string that contains data validating
Above pattern will also allow: -.00 or -0.00 as validate decimals.

Related

Checking digits with decimal separator defined

I have a function as below (I am not to much familiar with linq)
public static bool IsNumber(string s, char dec_sep)
{
return s.Length > 0 && s.All(c => Char.IsDigit(c));
}
If the number contains a decimal separator I get false as a fact.
I want to check if my defined decimal separator is in the number
Is it possible modify this function for this purpose ?
Or should I write another function ?
For being more clear
If in the string there ise decimal separator such as 72.5 it returns false (my defined separator is "." ). It already returns true if the string is 72 or 725.
I want this function returns TRUE even with a decimal separator.
I would advise against writing your own "IsNumber" function.
The framework already has TryParse of all built in value types - so I suggest using either float.TryParse, double.TryParse or decimal.TryParse depending on the size and precision of number you're expecting (23, 64 or 128 bit).
Writing your own "IsNumber" function is bound to have some difficulties, especially if you're going to attempt to parse user input (or any input you can't control, for that matter) - because like many other "simple" things, numbers are nothing but simple.
First, Numbers can have a thousands separator - in English, 1,234.56 is a valid number.
Second, string representations of numbers are culture dependent - 1,234.56 is invalid in some cultures - where the decimal separator is a comma and the thousands separator is a dot - so you would actually write it like this: 1.234,56
Note that these are two different ways to write the same number -
one thousand, two hundred thirty-four and fifty-six hundredths.
Even worst, you can write the same number in different numerals altogether - Thai, Arabic, Chinese or Hebrew - all of these languages (and probably many more languages) have their own symbols for numbers - and I'm not sure that IsDigit covers them all (though it's probably culture dependent also).
Having said all that, your current function will throw a NullReferenceException if the string is null - the very least you should do is either throw an ArgumentNullException or simply return false if the string is null.
Further more, there are going to be valid use-case where you want to know if a char exists exactly zero or once in a string - one way to do it is by subtracting IndexOf from LastIndexOf and check that the result of this subtruction is 0.
To combine that with your current method, you also want to change the condition in the All method to allow the char to either be a digit or your designated decimal separator.
If you really have to write your own method, here's how I would start it:
public static bool IsNumber(string s, char dec_sep)
{
return !string.IsNullOrEmpty(s)
&& s.LastIndexOf(dec_sep) - s.IndexOf(dec_sep) == 0
&& s.All(c => Char.IsDigit(c) || c == dec_sep);
}
The first condition will return false if the string is null or empty,
the second one will return false only if the string contains dec_sep more than once,
and the third will return false only if the string contains any char that is neither a digit nor dec_sep.
If you are a fan of regex you can also try "^\\d+\\.??(\\d*)?$"

Find integer in string using C# and divide it

I am trying to find the integers in a .txt that I am reading in C# and divide them, but everything I have tried have not worked. Any tips?
this txt has values like this:
this is the string in the .txt file
queue1 6000
queue2 54888
queue3 1
but they change every second
expected output
queue1 0.6
queue2 5.4
queue3 0.0001
code
int value;
string text = System.IO.File.ReadAllText(#"N:\doc\mytext.txt");
if (int.TryParse(text, out value))
{
value/10000;
}
Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine(text);
thanks
There are several things your code needs to do:
Read the input
Find the target values in the input
Convert the target values into the desired result values
Replace the target values in the input string with the result values
Output the result
For this answer, I am assuming you are happy with your implementation of steps 1 and 5, so I'll only address steps 2, 3, and 4.
Step 2: find the target values
To find the target values in your input, you must first define what they are. According to your question and subsequent comments, your input string looks like this, with the target values bolded:
queue1 6000, queue2 54888, queue3 1
These are integer values, which are embedded in your text as discrete words.
The easiest way to find them is to use a regular expression. One thing that makes your case tricky is the fact that you have numbers embedded in your text that you do not want (e.g. in "queue1"). Fortunately, .NET regular expressions have a couple shortcuts that make it easy to write the necessary expression:
var re = new Regex(#"\b\d+\b");
\b matches a word boundary
\d matches any decimal digit
+ matches one or more of the preceding characters
So this regular expression will match distinct integers like "6000" while ignoring numbers embedded in other words like "queue1".
Step 3 - convert to desired result
This step has a couple sub-steps
Parse the string into a number
Calculate the desired result number
Format the desired result number
To parse the string into a number, you are using int.TryParse, which is one way to do it. Since the regular expression will find only valid integers, we can use the Parse method instead.
Your calculation is to divide by 10000, and you want the result to be a floating point number. If you use 10000 as your literal, the result will be an integer, so you need to do something to ensure that the result is floating point. An easy way is to use 10000.0 as your literal, like so:
int value = 6000;
var result = value / 10000.0; // typeof(result) == double
There are several options to format your output. The simplest starting point is to use the ToString method. The default behavior is often good enough, but if you want to specify the format, you can use the variant that takes a format string.
So the resulting code to parse, calculate, and format is like so:
(Int64.Parse(value) / 10000.0).ToString()
Step 4: replace the target values in the input
Since regular expressions are useful for finding things, they are also used to replace things. In your case, the replacement requires some logic that may not be handled by a straight regular expression (i.e., step 2). The .NET regular expression Replace method provides an overload with a MatchEvaluator parameter for just this scenario.
Each match that is found by the regular expression is passed to the match evaluator, which is responsible for returning the string to be used as the replacement. To make things simple, you can use a lambda expression to supply the match evaluator.
So when you put it all together, you get something like this:
string text = #"queue1 6000, queue2 54888, queue3 1";
var re = new Regex(#"\b\d+\b");
string output = re.Replace(text, m => (Int64.Parse(m.Value) / 10000.0).ToString());
// output == "queue1 0.6, queue2 5.4888, queue3 0.0001"
You can use Regular expressions to get all of the numbers in a string. The string could be the content of a file that you got from System.IO.File.ReadAlltext (for example).
You can use "[0-9]+" to get all of the integers or "[0-9]+(.[0-9]+)?" to get both integers and floating points.
var pattern = "[0-9]" // or "[0-9]+(.[0-9]+)?"
int[] integers = System.Text.RegularExpressions.Regex.Matches(text, pattern).Cast<Match>().Select(m => int.Parse(m.Value)).ToArray();
// for floats
//float[] floats = System.Text.RegularExpressions.Regex.Matches(text, pattern).Cast<Match>().Select(m => float.Parse(m.Value)).ToArray();
In regular expressions you define a pattern then search the string for tokens that answer that pattern. If we need to search for integers then we can use the "[0-9]+" pattern. This pattern will search for all of the tokens that are between 0-9 (inclusive) with at least one character (one digit - the '+' make sure of that).
If we need to search for floating points then we need to use "[0-9]+(.[0-9]+)?" which is composed from the integers pattern ("[0-9]+") with addition to an optional floating point ("(.[0-9]+)?"). The '?' sign means that this token can exist zero or one time.
you can find more information about Regular Expressions and patterns here
You can use Regular Expressions for that:
Regex.Matches(text, #"(?<=^|\s)[0-9]+(?=$|\s)").Cast<Match>().Select(m => int.Parse(m.Value));
First, you select all parts of the string that resemble an integer, and then convert the resulting strings into integers.
(?=$|\s) is a Zero-width positive lookahead assertion. It checks if there is a whitespace or end of string at the end of the match.
(?<=^|\s) is a Zero-width positive lookbehind assertion. It checks if there is a whitespace or start of string at the beginning of the match.
You can find documentation on that here.
These are necessary so that the whitespaces are not included by the matches. If they were, you'd only get one of two integers if they are only separated by one whitespace.

Should not allow single zero or 0.##

How do I restrict single zero in a numeric (Decimal may alow) textbox? Textbox can accept any number but it should not accept only zero or "0.##" as value.
For example: "900.55", "200.00" is valid but "0" and "0.105"is invalid.
I tried ^[1-9]\d\.?\d[0-9]* but it accepting the "0" and "0.##"
You're almost there.
^[1-9][0-9]*(\.[0-9]+)?$
The input must
start with a number 1-9
be followed by any sequence of 0-9
and optional:
a dot followed by one or more 0-9.
Notes:
This also disallows 3.. If you don't want that, replace the last + with a *.
You can use \d instead of [0-9]. I've used the latter to stay consistent with [1-9] and keep things simple.
I think you're close, but it may be easier to include the decimal and following digits in a group and make that entire group only allowable once like this one:
^[1-9][0-9]*(\.\d*)?
Also, here's a useful site for testing regular expressions.
I think it would be simpler to do this:
float result;
return float.TryParse(textBox1.Text, out result) && result < 1;
If the textbox only accepts valid numbers, and all you want to assert is that it is > 0. All you really need then is
^[1-9]
or if trailing prefix zero's are allowed
^0*[1-9]
You could alternatively write it using a negative lookahead:
^(?!0\b)\d+(\.\d*)?$
This has the added bonus of accepting numbers with a preceding 0 like 022.
I faced the same situation and solve this.
try out it.
#"[^0]*[0-9].\d{2}$

Regex for allowing all other numbers like 1,10,15,90,92....etc except Zero?

Hi i have a senario where i have to prevent a field from entering zero by using Regex. But i have failed in creating the regex Can anybody help me in giving a correct regex?
What i have done is
^[1-9]\d{0,2}(\d*|(,\d{3})*)$
But this fails because it fails when a number contains zero like 340 is entered.
My senario is that the field must be able to accept all other integers except zero
How about this regex:
^[1-9][0-9]*$
String starts with 1 to 9 then has zero or more characters in 0 to 9.
It seems like regex might be overkill here. Why don't you try something like this:
int value;
if (Int32.TryParse(fieldString, out value))
{
if (value == 0)
{
// handle invalid value
}
}
This can be done with the pattern:
^(?![0,]+$)\d{0,2}(\d*|(,\d{3})*)$
Assuming you only want to accept positive integers. The pattern (?![0,]+$) prevents the expression from matching if it contains only zeros and commas. The second part is from the original expression, and allows the original combination of digits and commas for other values.
I assuming you'll be converting the field entry into an int? If so why not just do:
if (int == 0)
{
//not valid
}
However I'd hazard a guess you're using some kind of validation library?
You can try this one:
^[+-]?0*[1-9]\d*$
It accepts optional sign (plus or minus), then any number of leading zeroes, then at least one non-zero digit followed by any number of digits. You can see it in action at RegExr.

Parsing a decimal number

Guys, I have a string that contains a decimal number. The problem is, sometimes it is negative and it is stored in accounting format (positive number surrounded by parenthesis). In other words, I got a string like this:
string s = "(35.00)";
What I'm doing currently is:
decimal TheValue = decimal.Parse(s);
This value of TheValue should be -35.00. It apparently doesn't know what the parenthesis mean, so its just storing 0 in Thevalue. Anyone know how to make the decimal.Parse() function look for parenthesis?
Take a look at the decimal.Parse overload that accepts a NumberStyles enum. Specifically, you'll need to include NumberStyles.AllowParentheses.

Categories

Resources