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.
Related
I am trying to parse out and identify some values from strings that I have in a list.
I am using string.Contains to identify the value im looking for, but I am getting hits even if the value is surrounded by other text. How can I make sure I only get a hit if the value is isolated?
Example parse:
Looking for value = "302"
string sale =
"199708. (30), italiano, delim fabricata modella, serialNumber302. tnr F18529302E.";
var result = sale.ToLower().Contains(”302”));
In this example I will get a hit for "serialNumber302" and "F18529302E", which in the context is incorrect since I only want a hit if it finds “302” isolated, like “dontfind302 shouldfind 302”.
Any ideas on how to do this?
If you try Regex, you can define a word boundary using \b:
string sale =
"199708. (30), italiano, delim fabricata modella, serialNumber302. tnr F18529302E.";
bool result = Regex.IsMatch(sale, #"\b302\b"); // false
sale = "A string with 302 isolated";
result = Regex.IsMatch(sale, #"\b302\b"); // true
So 302 will only be found if it is at the start of the string, at the end of the string, or if it is surrounded by non-word characters i.e. not a-z A-Z 0-9 or _
EDIT: From the comments I realiſed that it waſn't clear whether or not "serialNum302" ſhould get a hit. I aſſumed ſo in this anſwer.
I ſee a few eaſy ways you could do this:
1) If the input is always a number as in the example, one option would be to only ſearch for ſubſtrings not ſurrounded by more numbers, by examining all the reſults of an initial ſearch and comparing their neighboring characters againſt the ſtring "0123456789". I really don't think this is the beſt option though, becauſe ſooner or later it's goïng to break when it miſinterprets one of the other bits of data.
2) If the ſtring sale always has the ſeriäl number in the format "serialNumber[Num]", inſtead of juſt looking for Num, look for "serialNumber" + Num, as this is leſs likely to be meſſed up with the other data.
3) From your ſtring, it looks like you have a ſtandardized format that's beïng introduced to the ſyſtem. In this caſe, parſe it in a ſtandardized way, e.g. by ſplitting it into ſubſtrings at the commas, then parſing each ſubſtring differently as it requires.
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.
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);
}
I am developing a web application where there is a textbox. User enters a condition to show specific color for a "string". This string holds some integer value.
User specifies condition for the string value like this,
>30:"Red"
<20:"Green"
:"Yellow:
This is one condition. It is something like if,elseif,else condition. User can specify only if,else like condition like this
>60:"Blue"
:"White"
(Which means if the string value greater than 60 then get "Blue" as color for the string else "White" is the color for the string)
I have to evaluate color for the string based on the above condition entered in the textbox for each string. There are thousands of strings with values and user will enter such expression for each string.
what is the best way to solve this issue?
String input = getTextBoxInput() // get input from text box
if(input.contains("<") || input.contains("<"))
{
if(input.contains("<"))
{
int index = input.indexOf("<");
String conditionString = input.substring(index+1,input.length());
// condition number is the number being compared
int conditionNumber = conditionString.split(":")[0];
// if condition is true then get the corresponding colour
if(number < conditionNumber){setColor(conditionString.split(":")[1])}
// check if it an if else condition and do the following
else if(input.length()>1){ setColor(conditionString.split(":")[2])}
}
}
This is the basic pseudo code. You can define constants for "<" and ">" . Also you may need to do some exception handling incase of incorrect input.
please see Shunting Yard algorithm , you need to have something similar
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.