My regex match positive real numbers doesn't work - c#

I am reading from a TextBox in C# and I want to make sure that only real positive values are allowed (including integers).
i.e. 1, 23, 23., 23.0, 23.42, etc.
The Regex I am using is:
[0-9]+\\.?[0-9]*
But C# does only let me type numbers and I can never put a period.
Thank you
Code:
private static readonly Regex rgx_onlyPositiveReals = new Regex("[0-9]+\\.?[0-9]*");
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsSamplingRateAllowed(e.Text);
}
private static bool IsSamplingRateAllowed(string text)
{
if(rgx_onlyPositiveReals.IsMatch(text))
{
if(text.Equals(".") || float.Parse(text) <= 0.0)
{
MessageBox.Show("Sampling Rate has to be positive.", "Wrong Sampling Frequency Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
return true;
}
return false;
}

From the looks of things this input box is supposed to only contain the number and no other text; in this case I would avoid the regular expression altogether.
Given that you're parsing the regex match result into a float anyway, it might make more sense to try parsing the input as a float directly which has the added benefits of allowing any valid positive float that can be parsed in the first place, it also allows entering the number in any other valid formats supported by float.Parse/float.TryParse e.g. scientific notation "1E5" == 100000f or commas "1,500" == 1500f (depending on the culture) without any additional effort.
private static bool IsSamplingRateAllowed(string text)
{
float number;
return float.TryParse(text, out number) && number >= 0.0f;
}
Unless this data is being used for some external process as a string with additional restrictions on the format (which seems unlikely and is worth including in the question if that is the case), then if it isn't already, I'd recommend separating this input box from any other information and have users enter the number and only the number directly into the box. If you need to collect other information from the user you can add other input boxes and controls as necessary (which can also simplify validation for other pieces of information).

Give this a try
The pattern is ^[0-9]+\.?[0-9]*
In C# you can prefix your string with # which makes it easier to read a regex. It results in the following:
"\\this \\is \\the \\same" == #"\this \is \the \same"

You can simply use the below Regex
^\d*[.]?\d*$
Demo Fiddle

Related

C# strip out not needed data using REGEX or something different

So i'm trying to strip data from a string because I have in WPF a "preset" input which looks like __,___, now a user must input something like 30,589, but when a user just gives in 5 or 50, it needs to strip the rest (keeping the ,) to propperly make a float of the input value. The code that I have right now looks like this;
if (inp_km.Text == "__,___")
{
team_results.results[inp_tour_part.SelectedIndex].km =
float.Parse("00,000",
NumberStyles.AllowDecimalPoint,
CultureInfo.GetCultureInfo("nl-NL")); // Give the new value
}
else
{
team_results.results[inp_tour_part.SelectedIndex].km =
float.Parse(inp_km.Text,
NumberStyles.AllowDecimalPoint,
CultureInfo.GetCultureInfo("nl-NL")); // Give the new value
}
But this code just check wether the input is left blank or not... Could someone help me out?
Edit
So I've included a screen, this is the input lay-out a user gets;
Os you can see, the inputs are 'pre-filled', the content of such an input is a "string", so, let's say, I type into the first input just 5;
Then the value (retreived in C# by input_name.Text) is 5_:__, but that's a "wrong" value and you can't fill in such things, how could I check if there still is a : or _ in the input.
Also, the bottom input is the same, but then it needs to be filled in completely.
So you want to check either the input is in one of the two forms: 12,345 or 12:34.
This can be done using Regex very easily.
static void Main(string[] args)
{
var inputComma = "12,345";
var inputColon = "98:76";
Regex regexComma = new Regex(#"^\d{2},\d{3}$");
Regex regexColon = new Regex(#"^\d{2}:\d{2}$");
var matchComma = regexComma.Match(inputComma);
if (matchComma.Success)
{
Console.WriteLine(inputComma);
}
Console.WriteLine();
var matchColon = regexColon.Match(inputColon);
if (matchColon.Success)
{
Console.WriteLine(inputColon);
}
Console.ReadLine();
}
NOTE:
You haven't quite clarified the valid formats for your input. The above will evaluate to true strictly for 12,345 format if commas are present (i.e., two digits followed by a comma followed by three digits), and for colon, only numbers of the format 12:34 (two digits before and after the colon) only.
You might want to modify your Regex based on your exact criteria.

Basic Regex help needed

I'm really new to programming and haven't come across Regex until now, I am looking to restrict textbox input to double class values only and came across this:
`Regex regex = new Regex("[^0-9-]+");
TextP1_TextChanged = regex.IsMatch(TextP1.Text);`
I want to implement into my program and am assuming it occurs under the TextChanged event, but I don't actually have the knowledge to implement regex and so am just looking for any help.
Update
I've implemented TryParse but am looking to accept decimal numbers with or without 0 in front, i.e. 0.234 or .234. My new code is this:
private void TextP1_TextChanged(object sender, EventArgs e)
{
bool isDouble = Double.TryParse(TextP1.Text, out P1);
if(isDouble == false)
{
MessageBox.Show("Text box only accepts positive number values", "Text entered into P1 is invalid", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You could use this regular expression [0-9]*\.[0-9]*. The * means 0-9 can occur 0 to x times.
You could use regexr to test regular expression in a fast way.

How to check if the tape starts with special characters

I need to track to string began with the required letters (Cyrillic or Latin or even any letters). But definitely not with numbers or special characters including space.
For start my task was only hanlde string starts with number but for now also certain characters.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int i;
if (isRoot && (int.TryParse(textBox1.Text.Trim(), out i)))
What should I do for characters?? Use something like this (but in this case I need to make conditions for all characters):
(textBox1.Text.Trim(). StartsWith("%") || textBox1.Text.Trim().StartsWith("-") || ......
)
Is there some better ways?? Coz if you propose to allow only letters then it is a bad idea because it can be given a different language.. So what?
You can use a Regular Expression to handle this functionality.
For example:
This snippet makes sure an input file path is correctly formatted.
// [drive_letter]:\ or \\[server]\ or [drive name]:\
private const string PathPattern = "^[A-z]:[\\\\/]|^\\\\|^.*[A-z]:[\\\\/]";
var matchMaker = new Regex(PathPattern);
var success = matchMaker.Matches(inputPath);
In your case you want to identify different characters and trim them, so you'd identify those strings with a Regex expression then carry out your parsing logic.
This link has a list of all the Regex commands:
http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

TextBox Validation - C#

I am having quite a hard time with my C# Application's textbox validation. The thing is, the said textbox should only accept decimal values. so it means, there should be no letters or any other symbols aside from the '.' symbol. The letter filter, i can handle. However, i don't exactly know how I can manage to filter the number of '.' that the textbox should accept. If anybody has any idea how to do this, please give me an idea.
Thank you very much :)
decimal value;
bool isValid = decimal.TryParse(textBox.Text, out value);
if (!isValid)
{
throw new ArgumentException("Input must be a decimal value");
}
this should work!!!
modified for just one decimal
private void txtType_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back || (e.KeyChar == (char)'.') && !(sender as TextBox).Text.Contains("."))
{
return;
}
decimal isNumber = 0;
e.Handled = !decimal.TryParse(e.KeyChar.ToString(), out isNumber);
}
Use regex validation:
^([0-9]*|\d*\.\d{1}?\d*)$
This site has a library of regex validation (including numeric related) that you'll find useful:
http://regexlib.com/Search.aspx?k=decimal&c=-1&m=-1&ps=20
Just a thought: if you are monitoring the decimal places, simply keep a bool flag in your control to say "I've already had a dot"; subsequent dots are invalid.
Alternatively, when checking for decimal places, you can use Contains:
if (textbox.Text.Contains("."))
Also, review this sample available on MSDN (NumericTextBox):
http://msdn.microsoft.com/en-us/library/ms229644(VS.80).aspx
Use a MaskedTextBox instead and set the mask to only accept decimals.

Allow user to only input text?

how do I make a boolean statement to only allow text? I have this code for only allowing the user to input numbers but ca'nt figure out how to do text.
bool Dest = double.TryParse(this.xTripDestinationTextBox.Text, out Miles);
bool MilesGal = double.TryParse(this.xTripMpgTextBox.Text, out Mpg);
bool PriceGal = double.TryParse(this.xTripPricepgTextBox.Text, out Price);
Update: looking at your comment I would advise you to read this article:
User Input Validation in Windows Forms
Original answer: The simplest way, at least if you are using .NET 3.5, is to use LINQ:
bool isAllLetters = s.All(c => char.IsLetter(c));
In older .NET versions you can create a method to do this for you:
bool isAllLetters(string s)
{
foreach (char c in s)
{
if (!char.IsLetter(c))
{
return false;
}
}
return true;
}
You can also use a regular expression. If you want to allow any letter as defined in Unicode then you can use this regular expression:
bool isOnlyLetters = Regex.IsMatch(s, #"^\p{L}+$");
If you want to restrict to A-Z then you can use this:
bool isOnlyLetters = Regex.IsMatch(s, #"^[a-zA-Z]+$");
You can use following code in the KeyPress event:
if (!char.IsLetter(e.KeyChar)) {
e.Handled = true;
}
You can use regular expression, browse here: http://regexlib.com/
You can do one of a few things.
User Regular Expression to check that the string matches your concept of 'Text' only
Write some code that checks each character against a list of valid characters. Or even use char.IsLetter()
Use the MaskedTextBox and set a custom mask to limit input to text only characters
I found hooking up into the text changed event of a textbox and accepting/rejecting the changes an acceptable solution. To "only allow text" is a rather vague definition, but you may as well check if your newly added text (the next char) is a number or not and simply reject all numbers/disallowed characters. This will make users feel they can only enter characters and special characters (like dots, question marks etc.).
private void UTextBox_TextChanged(object sender, EventArgs e)
{
string lastCharacter = this.Text[this.Text.Length-1].ToString();
MatchCollection matches = Regex.Matches(lastCharacter, "[0-9]", RegexOptions.None);
if (matches.Count > 0) //character is a number, reject it.
{
this.Text = Text.Substring(0, Text.Length-1);
}
}

Categories