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

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.

Related

Remove several dots/commas in string from every decimal number

How can I check for a comma in a number?
Lets assume I have a string which represents a polynomial term that looks like this
string x = "x+1+5,54";
Now the user wants to put in and add a comma which will then be "x1+5,54,"
which is not a number anymore. How can I check this with an if ?
Something like if the last number already contains a comma don't append another one.
Use regular expression.
if (Regex.IsMatch(a, #"^((\d+,?\d*)|(\w?))([-+/]((\d+,?\d*)|(\w?)))*$"))
{
//correct
}
else
{
//incorrect
}
You'll get false, when user inputs extra comma, so you can handle it.

How do I make regex properly validate the information?

I've been given the task to make a textbox where you enter your personal code (something we in Latvia use). I need it to be validated before saving the information. For validation I've been using Regex but so far got no result.
Our personal code is like this : XXYYZZ-ABCDE, where
XXYYZZ is date format as in DAYMONTHYEAR and ABCDE are random numbers.
if (per_kods.Text.Trim() != string.Empty)
{
mRegxExpression = new Regex("${day}-${month}-${year}-#####$");
if (!mRegxExpression.IsMatch(per_kods.Text.Trim()))
{
label7.Text = "";
}
else
{
label7.ForeColor = Color.Red;
label7.Text = "Personas kods ievadīts nepareizi!";
pareizi = false;
}
}
this currently is my code. It basically enables a label above the textbox pointing out that the information entered is wrong. If the information is right, the label continues to be disabled. But right now the new Regex part is a problem. I know it might seem totally wrong, but I've just started learning Regex and don't know what's wrong and what's right.
If you don't care about date validation (so for example 31st of February will be accepted, you can do
new Regex(#"^(0[1-9]|[1-2]\d|3[0-1])(0[1-9]|1[0-2])(\d{2})-(\d{5})$");
If you want to understand what this string means, take a look at the MSDN reference.
Now for date validation, so filtering out dates like 310298 that don't exist, I'd recommend you do it manually afterwards - regex is not the best tool for such logic-validation.
EDIT:
You can accomplish that using DateTime.TryParse.
DateTime resultDateTime;
var isValid = DateTime.TryParse(string.Format("{0}-{1}-{2}", 2010, 2, 31), out resultDateTime);
// isValid is false, because 31st of February 2010 does not exist.
var isValid = DateTime.TryParse(string.Format("{0}-{1}-{2}", 2010, 2, 27), out resultDateTime);
// isValid is true, and resultDateTime has been set to 27-2-2010.
Note that DateTime.TryParse is culture sensitive. Depending on the target culture you might need to change the input string. See MSDN reference for TryParse.
EDIT2:
So to connect this with your existing code:
mRegxExpression = new Regex(#"^(0[1-9]|[1-2]\d|3[0-1])(0[1-9]|1[0-2])(\d{2})-(\d{5})$");
var match = mRegxExpression.Match(per_kods.Text.Trim()));
if(!Validate(match))
{
// Handle invalid.
}
else
{
// Handle valid.
}
Where Validate would be:
private static bool Validate(Match match)
{
if(!match.Success)
{
return false;
}
var day = match.Groups[1].ToString();
var month = match.Groups[2].ToString();
var year = match.Groups[3].ToString();
return DateTime.TryParse($"{day}-{month}-{year}", out _);
}
Because our regex begins with ^ and ends with $, there will be always at most one match. The Success property tells us whether there was any match at all, and later the Groups property gives us the capture groups. Groups[0] will be the entire matched string, and then every next one will be the substring that matches one of the parentheses enclosed groups from regex - so the first one is (0[1-9]|[1-2]\d|3[0-1]) which represents days, the second will be months, and so on. Then we just check if the date is valid (again, culture sensitive!). Also, we can neatly use the C#7 discard syntax (_) for the out parameter, as we don't need it.
You can get help from the code below to check validation.
public bool CheckValidation(string input)
{
input = input.Trim();
if (input == string.Empty) return false;
var mRegxExpression = new Regex("^([0-2][0-9]|(3)[0-1])(((0)[0-9])|((1)[0-2]))\\d{2}(\\-)\\d{5}$");
return mRegxExpression.IsMatch(input);
}

Format String to Match Specific Pattern

I am trying to figure out how to format a string to a specific pattern.
When a user is entering their employee id number, they often get confused on what is expected from them. Because they are often told that their employee id is either a 5 digit or 4 digit number depending on when they were hired.
For example, my employee id number is E004033 but for most of our systems, I just have to enter 4033 and the system will find me.
We are trying to add this to one of our custom pages. Basically what I want to do is format a string to always look like E0XXXXX
So if they enter 4033 the script will convert it to E004033, if they enter something like 0851 it will convert it to E000851 or if they enter 11027 it will convert it to E011027
Is there a way basically add padding zeros and a leading E if they are missing from the users input?
You can simply:
var formattedId = "E" + id.PadLeft(6, '0');
To remove an existing leading E(s)
var text = "E" + val.TrimStart(new[] {'E'}).PadLeft(6, '0');
Make sure the user's input is an integer, then format to 6 spaces using String.Format.
int parsedId;
bool ok = int.TryParse(id, out parsedId);
if (ok)
{
return String.Format("E{0:000000}", parsedId);
}

Adding comma between longer numbers [duplicate]

This question already has answers here:
.NET String.Format() to add commas in thousands place for a number
(23 answers)
Closed 9 years ago.
I'm trying to put comma's between long numbers automatically, but so far without success. I'm probably making a very simple mistake, but so far I can't figure it out. This is the code I currently have, but for some reason I'm getting 123456789 as the output.
string s = "123456789";
string.Format("{0:#,###0}", s);
MessageBox.Show(s); // Needs to output 123,456,789
var input = 123456789;
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
If, as per your question, you need to start with a string:
var stringInput = "123456789";
var input = int.Parse(stringInput);
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
You'll possibly also need to take culture into account when parsing/formatting. See the overloads that take an IFormatProvider.
Try this:
string value = string.Format("{0:#,###0}", 123456789);
In your code you are missing the initial { in the format string, and then number formatting options apply to numbers, while your s is a string.
You could convert the string to a number with int.Parse:
int s = int.Parse("123456789");
string value = string.Format("{0:#,###0}", 123456789);
MessageBox.Show(value);
This should work (you need to pass String.Format() a number, not another String):
Int32 i = 123456789;
String s = String.Format("{0:#,###0}", i);
MessageBox.Show(s);
But consider the format string you're using...there are cleaner options available, as others are suggesting.
Look at the number formatting information on MSDN: Standard Numeric Format Strings, or optionally at the custom format strings: Custom Numeric Format Strings.
For custom number formats:
The "," character serves as both a group separator and a number scaling specifier.
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,567,890
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235
There is so much wrong with your code, that's it's hard to describe every detail.
Look at this example:
namespace ConsoleApplication1
{
using System;
public class Program
{
public static void Main()
{
const int Number = 123456789;
var formatted = string.Format("{0:#,###0}", Number);
Console.WriteLine(formatted);
Console.ReadLine();
}
}
}

C# Regex.Match to decimal

I have a string "-4.00 %" which I need to convert to a decimal so that I can declare it as a variable and use it later. The string itself is found in string[] rows. My code is as follows:
foreach (string[] row in rows)
{
string row1 = row[0].ToString();
Match rownum = Regex.Match(row1.ToString(), #"\-?\d+\.+?\d+[^%]");
string act = Convert.ToString(rownum); //wouldn't convert match to decimal
decimal actual = Convert.ToDecimal(act);
textBox1.Text = (actual.ToString());
}
This results in "Input string was not in a correct format." Any ideas?
Thanks.
I see two things happening here that could contribute.
You are treating the Regex Match as though you expect it to be a string, but what a Match retrieves is a MatchGroup.
Rather than converting rownum to a string, you need to lookat rownum.Groups[0].
Secondly, you have no parenthesised match to capture. #"(\-?\d+\.+?\d+)%" will create a capture group from the whole lot. This may not matter, I don't know how C# behaves in this circumstance exactly, but if you start stretching your regexes you will want to use bracketed capture groups so you might as well start as you want to go on.
Here's a modified version of your code that changes the regex to use a capturing group and explicitly look for a %. As a consequence, this also simplifies the parsing to decimal (no longer need an intermediary string):
EDIT : check rownum.Success as per executor's suggestion in comments
string[] rows = new [] {"abc -4.01%", "def 6.45%", "monkey" };
foreach (string row in rows)
{
//regex captures number but not %
Match rownum = Regex.Match(row.ToString(), #"(\-?\d+\.+?\d+)%");
//check for match
if(!rownum.Success) continue;
//get value of first (and only) capture
string capture = rownum.Groups[1].Value;
//convert to decimal
decimal actual = decimal.Parse(capture);
//TODO: do something with actual
}
If you're going to use the Match class to handle this, then you have to access the Match.Groups property to get the collection of matches. This class assumes that more than one occurrence appears. If you can guarantee that you'll always get 1 and only 1 you could get it with:
string act = rownum.Groups[0];
Otherwise you'll need to parse through it as in the MSDN documentation.

Categories