RegEx for Both Integer & Float - c#

I need a RegEx to match both Integer values as well as Float numbers.
and i want to use it using *Regular Expression Validator *
What should be Valid:
.1
.12
1.2
1.23
12.3
12.34
1
12
What should be Invalid:
.123(this value is having more then 2 decimal values)
1.234(this value is having more then 2 decimal values)
What i exactly want is to take values from 0 to 99.99 only in TextBox(MaxLength=5) Control in ASP.Net with C#.

you want a regex like this
^(?:\d{1,2})?(?:\.\d{1,2})?$
here the non capturing group (?:\d{1,2}) will check for values between 0 - 99.
this has been made optional with ? because values like .12 , .2 are permitted.
demo here : http://regex101.com/r/oW7rF4

You can implement a check like this:
String string = "1.23";
if(
string.match(/^\d+$/) || // for "123", "456"
string.match(/^\d+\.\d{1,2}$/) || // for "123.45", "4.5"
string.match(/^\.\d{1,2}$/) ) // for ".45", ".8"
// do something
else
// do something else
Note: This is a pseudo-code (or whatever you call it), you can convert it to your language.

(^\d{1,2}$)|(^\d{0,2}[.]\d{1,2}$)
(^\d{1,2}$) is for INT
[0 , 1 , 12 , 99]
(^\d{0,2}[.]\d{1,2}$) is for FLOAT
[.1 , .12 , 1.2 , 1.23 , 12.3 , 12.34 , .99 , 99.99]

Related

how to convert a number to decimal formated value in c#?

Which string format can convert this:
1 to 0.01
12 to 0.12
123 to 1.23
1234 to 12.34
12345 to 123.45
Inside my xamarin forms if a user types this number to an entry then it will automatically format that number. What is the string format of that?
For example: Text={Binding Price,StringFormat='${0:F0}'}
Seems like you just want division
var result = value / 100m;
Console.WriteLine(result);
--
Additional Resources
Division operator /
You can divide by 100, as others are saying, followed by applying the desired numeric formats.
Just as Michael Randall said above it's simple as that, in addiction you can check if it can be parsed first, something like this:
bool success = decimal.TryParse(value , out number);
if(success)
var result = value / (decimal)100
else
//Handle incorrect user input

MaskInput number format show dash (-) instead of zero

Want to format my number value if number is zero then should show dash ('-') sign instead of zero. what would be the format or MaskInput?
e.g.:
========================================
MyNumberFormatted MyNumberNoFormat
========================================
- 0
5 5
- 0
1 1
========================================
Conditional formatting
string conditionalFormat = "{0:##;-##;-}"; // {0:positive;negative;zero}
Console.WriteLine(string.Format(conditionalFormat, 1));
Console.WriteLine(string.Format(conditionalFormat, -1));
Console.WriteLine(string.Format(conditionalFormat, 0));
https://dotnetfiddle.net/BgFc8j

C# - Getting multiple values with a single key, from a text file

I store multiple values that shares a single key on a text file. The text file looks like that:
Brightness 36 , Manual
BacklightCompensation 3 , Manual
ColorEnable 0 , None
Contrast 16 , Manual
Gain 5 , Manual
Gamma 122 , Manual
Hue 0 , Manual
Saturation 100 , Manual
Sharpness 2 , Manual
WhiteBalance 5450 , Auto
Now I want to store the int value & string value of each key (Brightness, for example).
New to C# and could'nt find something that worked yet.
Thanks
I'd recommend to use custom types to store these settings like these:
public enum DisplaySettingType
{
Manual, Auto, None
}
public class DisplaySetting
{
public string Name { get; set; }
public decimal Value { get; set; }
public DisplaySettingType Type { get; set; }
}
Then you could use following LINQ query using string.Split to get all settings:
decimal value = 0;
DisplaySettingType type = DisplaySettingType.None;
IEnumerable<DisplaySetting> settings = File.ReadLines(path)
.Select(l => l.Trim().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries))
.Where(arr => arr.Length >= 3 && decimal.TryParse(arr[1], out value) && Enum.TryParse(arr[2], out type))
.Select(arr => new DisplaySetting { Name = arr[0], Value = value, Type = type });
With a regex and a little bit of linq you can do many things.
Here I assume you Know How to read a Text file.
Pros: If the file is not perfect, the reg exp will just ignore the misformatted line, and won't throw error.
Here is a hardcode version of your file, note that a \r will appears because of it. Depending on the way you read you file but it should not be the case with a File.ReadLines()
string input =
#"Brightness 36 , Manual
BacklightCompensation 3 , Manual
ColorEnable 0 , None
Contrast 16 , Manual
Gain 5 , Manual
Gamma 122 , Manual
Hue 0 , Manual
Saturation 100 , Manual
Sharpness 2 , Manual
WhiteBalance 5450 , Auto";
string regEx = #"(.*) (\d+) , (.*)";
var RegexMatch = Regex.Matches(input, regEx).Cast<Match>();
var outputlist = RegexMatch.Select(x => new { setting = x.Groups[1].Value
, value = x.Groups[2].Value
, mode = x.Groups[3].Value });
Regex explanation:/(.*) (\d+) , (.*)/g
1st Capturing Group (.*)
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
matches the character literally (case sensitive)
2nd Capturing Group (\d+)
\d+ matches a digit (equal to [0-9])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
, matches the characters , literally (case sensitive)
3rd Capturing Group (.*)
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Disclamer:
Never trust an input! Even if it's a file some other program did, or send by a customer.
From my experience, you have then two ways of handeling bad format:
Read line by line, and register every bad line.
or Ignore them. You don't fit , you don't sit!
And don't tell your self it won't happend, it will!

Regex (.NET) to validate any real number in several formats

I am trying to validate any real number in different formats using one regex rule in .NET. The formats I mean are the following:
Dots (thousands) and comma (decimal)
123 ; 1.234.567 ; 12.345.678 ; 123.456.789 ; 1.234.567,89 ; 1.234,56789 ; 1,2 ; 0,123
Commas (thousands) and dot (decimal)
1,234,567 ; 12,345,678 ; 123,456,789 ; 1,234,567.89 ; 1,234.56789 ; 1.2 ; 0.123
White space (thousands) and dot or comma (decimal)
1 234 567 ; 12 345 678 ; 123 456 789 ; 1 234 567,89 ; 1 234 567.89 ; 1 234,56789 ; 1 234.56789
I know a bit more that the basics about regex, so I have done this. No success so far.
(^|\s)(-|\+|±|\+/-)?(?:(([1-9]{1,3})([,]\d{3})*|[0]?)([\.]\d+)?)|(?:(([1-9]{1,3})([\.]\d{3})*|[0]?)([,]\d+)?)|(?:(([1-9]{1,3})([\s]\d{3})*|[0]?)([\.|,]\d+)?)(\s|$)
Can any one help me or link me to the solution if it is out there?
Well, this may not be the optimal regex:
^\d*$|^(?:\d{1,3}(?:\.\d{3})*(?:,\d{1,5})?)$|^(?:\d{1,3}(?:,\d{3})*(?:\.\d{1,5})?)$|^(?:\d{1,3}(?: \d{3})*(?:[,.]\d{1,5})?)$
But it does the job. I'll look how to make a better one in a near future. Here's a Live Demo
If your input is not that dirty (ie: once you have a space as a thousand separator you don't get dot then comma, not like 1 032,354.12) you can use this simple version:
^\d{1,3}(?:[., ]\d{3})*(?:[.,]\d{1,5})?$
Which means:
\d{1,3} <= start with 1 to 3 digit;
(?:[., ]\d{3})* <= thousand separator with 3 digit after repeated 0 to n times;
(?:[.,]\d{1,5})? <= decimal separator with 1 to 5 digit after it, 0 or 1 time.

Regex for validation of many types of number

I'm new to Regex and I would like to know how do I detect the number by Regex in C#, that always display in a format : #,###
Ex : 2 000,000 into 2,000
Ex : 15 000.000 into 15,000
Ex : 6.700 into 6,700
Ex : .3.3.3 into 0,300
These are some examples that I'm doing for validation
As the comments suggest, the question is not very clear.
To get your examples working, you can use e.g.
(?:(?<int>\d+)[ .,]?|[.,])
(?<frac>\d+)?
(?:[ .,]\d+)*
to match the "integer part" and the "fractional part" divided by ., , or (wired, but that is what I read out of your examples - since 15 000.000 => 15,000 and 6.700 => 6,700 I assume a comma seperator everywhere).
I'm pretty sure I did not get it right! At least not entirely. The examples you provide look like numbers with different thousands separator, but it seems to have no system.
However, this is what you match with the regular expression above:
int | | frac | anything else
----+-+------+--------------
2 | | 000 | ,000
15 | | 000 | .000
6 |.| 70 |
|.| 3 | .3.3
In addition, it matches numbers without fractional part.
In Detail
(?:(?<int>\d+)[ .,]?|[.,])
Match decimals (one ore more) and store them in a group named int. Match an optional , . or , thereafter.
OR
Match . or ,.
(?<frac>\d+)?
Optionally match the fraction part (one or more decimals).
(?:[ .,]\d+)*
Match , . or , and one or more decimals (repeat this zero or more times).
This last one is to prevent the last parts of e.g. .3.3.3 to match in subsequent calls.
Next
Then you can use a MatchEvaluator-Function (here in form of a delegate) to replace the values.
var rx = new Regex(#"
(?:(?<int>\d+)[ .,]?|[.,])
(?<frac>\d+)?
(?:[ .,]\d+)*
",
RegexOptions.IgnorePatternWhitespace
);
var deDE = new System.Globalization.CultureInfo("de-DE");
text = rx.Replace(text, delegate(Match match) {
int integral;
int fraction;
int fraclen = match.Groups["frac"].Length;
int.TryParse(match.Groups["int"].Value, out integral);
int.TryParse(match.Groups["frac"].Value, out fraction);
var val = integral + fraction / Math.Pow(10, fraclen);
return String.Format(deDE, "{0:0.000}", val);
});
The function is called for every match. Inside, I read out the groups, convert them into integers and then create the matched value with integral + fraction / Math.Pow(10, fraclen) (integral part + fraction part divided by 10^len where len is the string-length of the fraction part, thus "70" becomes 0.7 by calculating 70/10^2 == 70/100 == 0.7).
At the end, I return String.Format with CultureInfo de-DE. This is done because in Germany you use , as decimal seperator. There are others too - and there are many other ways to output such a number..
This is just an example.

Categories

Resources