(Calculator program)count in one step with math basic order
if there is a string = "5+2*6/9"(which is user input) how to get number 2 and 6?
i've been trying with split but if there is no '+' it fail :(
here is my code atm
string[] a = kalimat.Split('*');
string[] a1 = a[0].Split('+');
string[] a2 = a1[a1.Count() - 1].Split('-');
string[] b1 = a[1].Split('+');
string[] b2 = b1[0].Split('-');
ang1 = a2[a2.Count() - 1];
ang2 = b2[0];
angka1 = Convert.ToDouble(ang1);
angka2 = Convert.ToDouble(ang2);
hasil = angka1 * angka2;
any idea guys?
If you're input expression is always in the form: "[some number]+[first value you want to return]*[second value you want to return]" then this should work for you:
var reg = new System.Text.RegularExpressions.Regex(#"\d\+(\d)\*(\d)");
var result = reg.Match("5+2*6/9");
var first = result.Groups[1];
var second = result.Groups[2];
You can of course tweak the regular expression search pattern to suit your needs.
Parsing arbitrary mathematical expression is not a trivial task. If this isn't a homework that require you to do the parsing by hand, I would suggest to find a library for doing the task, like NCalc for example.
You can install it from Nuget, and use the following simple code :
var kalimat = "5+2*6/9";
var hasil = new NCalc.Expression(kalimat).Evaluate();
Console.WriteLine(hasil);
Selamat mencoba :)
Related
Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.
I have real time response from web service as follows :
ok,SIP/2417,15,default,N
I can save this in text file.
The only thing change is 2417 and 15.
Now I want to explode 2417 and 15 from text file and save in variable or database.
For Database I have Column Ext and Ringtime
This should work:
var test = "ok,SIP/2417,15,default,N";
var regex = new Regex("^ok,SIP/(?<number1>\\d+),(?<number2>\\d+),default,N$");
var match = regex.Match(test);
var val1 = match.Groups["number1"].Value;
var val2 = match.Groups["number2"].Value;
But this would also work:
var test = "ok,SIP/2417,15,default,N";
var values = test.Split(',');
var val1 = values[1].Substring(4);
var val2 = values[2];
Note that they will still be strings at this stage, so you'll need to parse them if you require them as integers:
var number1 = int.Parse(val1);
var number2 = int.Parse(val2);
** TryParse is a better option if you go with the Split option.
Try it online
If you want to have a generic regex you can try is
Regex r = new Regex(#"([\d]+,[\d]+)");
string var = "ok,SIP/2417,15,default,N";
Match match = r.Match(var);
if you want list of those vars then below is the dynamic solution for any count of number.
List<int> vals = new List<int>();
vals.AddRange(match.Groups[0].Value.Split(',').Select(x => Convert.ToInt32(x)));
else if you're going to have fixed two values then.
int val = Convert.ToInt32(match.Groups[0].Value.Split(',')[0]);
int val2 = Convert.ToInt32(match.Groups[0].Value.Split(',')[1]);
I am most familiar with PowerShell and have recently moved into using C# as my primary language. In PowerShell it's possible to do the following
$var1 = "abc"
"abc" -match "$var1"
This results in a true statement.
I would like to do be able to do the same thing in C#. I know that you can use interpolation with C# and I have tries various ways of trying to use Regex.Match() with no luck.
Example:
string toMatch = "abc";
var result = Regex.Match("abc", $"{{toMatch}}");
var a = Regex.Match("abc", $"{{{toMatch}}}");
var b = Regex.Match("abc", $"{toMatch}");
var c = Regex.Match(toMatch,toMatch);
None of the above seems to work. I am not even sure if what I am trying to do is possible in C#. Ideally I'd like to be able to use a combination of variables and Regex for a match. Something even like this Regex.Match(varToMatch,$"{{myVar}}\\d+\\w{4}")
edit:
After reading some answers here and trying some code out it appears that my real issue is trying to match up against a directory path. Something like "C:\temp\abcfile". For example:
string path = #"C:\temp\abc";
string path2 = #"C:\temp\abc";
string fn = path.Split('\\').LastOrDefault();
path = Regex.Escape(path);
path2 = Regex.Escape(path2);
Regex rx = new Regex(path);
var a = Regex.Match(path.Split('\\').Last().ToString(), $"{fn}");
//Example A works if I split and match on just the file name.
var b = Regex.Match(path, $"{rx}");
//Example B does not work, even though it's a regex object.
var c = Regex.Match(path, $"{{path}}");
//Example C I've tried one, two, and three sets of parenthesis with no luck
var d = Regex.Match(path,path);
// Even a direct variable to variable match returns 0 results.
You seem to have it right in the last example, so perhaps the issue is that you're expecting a bool result instead of a Match result?
Hopefully this small example helps:
int a = 123;
string b = "abc";
string toMatch = "123 and abc";
var result = Regex.Match(toMatch, $"{a}.*{b}");
if (result.Success)
{
Console.WriteLine("Found a match!");
}
I have string COO70-123456789-12345-1. I need to parse based on the "-" not the length of the substrings and use the parsed values. I have tried using Regular expressions but having issues.Please suggest.
Also after I have split the values I need to use each values: string A = COO70, int B = 123456789, int C = 12345, short D = 1 . How do I get it in different variables A,B,C,D.
string[] results = UniqueId.Split('-');
string A = results[0];
string B = results[1];
string C = results[2];
int k_id = Convert.ToInt32(k_id);
string D = results[3];
short seq = Convert.ToInt16(seq);
string s = "COO70-123456789-12345-1";
string[] split = s.Split('-'); //=> {"COO70", "123456789", "12345", "1"}
Use indexOf
To find everything before the first hyphen use:
string original= "COO70-123456789-12345-1";
string toFirstHyphen=original.Substring(0,original.IndexOf("-"));
Or if you want every section use split like the above example.
You can verify whether the input is formatted as you want and then split to get the parts.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = #"(?x)^(\w+-\w+-\w+-\w+)$";
Regex reg = new Regex(pattern);
string test = "word-6798-3401-001";
if((reg.Match(test).Success))
foreach (var x in test.Split(new char[] {'-'}))
Console.WriteLine(x);
}
}
So it sounds like you first want to split it, but then store it into your values.
I would do something like this:
var myString = "COO70-123456789-12345-1";
var stringSet = myString.Split("-"); // This returns an array of values.
Now we need to verify that we receive only 4 sub strings:
if (stringSet.Count != 4)
throw Exception e; // Throw a real exception, not this
From here we need to know what order our strings should be in and assign them:
var A = stringSet[0];
var B = stringSet[1];
var C = stringSet[2];
var D = stringSet[3];
While this should answer your question as posed, I would recommend you work with stringSet differently personally.
I am trying to process a report from a system which gives me the following code
000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}
I need to extract the values between the curly brackets {} and save them in to variables. I assume I will need to do this using regex or similar? I've really no idea where to start!! I'm using c# asp.net 4.
I need the following variables
param1 = 000
param2 = GEN
param3 = OK
param4 = 1 //Q
param5 = 1 //M
param6 = 002 //B
param7 = 3e5e65656-e5dd-45678-b785-a05656569e //I
I will name the params based on what they actually mean. Can anyone please help me here? I have tried to split based on spaces, but I get the other garbage with it!
Thanks for any pointers/help!
If the format is pretty constant, you can use .NET string processing methods to pull out the values, something along the lines of
string line =
"000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}";
int start = line.IndexOf('{');
int end = line.IndexOf('}');
string variablePart = line.Substring(start + 1, end - start);
string[] variables = variablePart.Split(' ');
foreach (string variable in variables)
{
string[] parts = variable.Split('=');
// parts[0] holds the variable name, parts[1] holds the value
}
Wrote this off the top of my head, so there may be an off-by-one error somewhere. Also, it would be advisable to add error checking e.g. to make sure the input string has both a { and a }.
I would suggest a regular expression for this type of work.
var objRegex = new System.Text.RegularExpressions.Regex(#"^(\d+)=\[([A-Z]+)\] ([A-Z]+) \{Q=(\d+) M=(\d+) B=(\d+) I=([a-z0-9\-]+)\}$");
var objMatch = objRegex.Match("000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}");
if (objMatch.Success)
{
Console.WriteLine(objMatch.Groups[1].ToString());
Console.WriteLine(objMatch.Groups[2].ToString());
Console.WriteLine(objMatch.Groups[3].ToString());
Console.WriteLine(objMatch.Groups[4].ToString());
Console.WriteLine(objMatch.Groups[5].ToString());
Console.WriteLine(objMatch.Groups[6].ToString());
Console.WriteLine(objMatch.Groups[7].ToString());
}
I've just tested this out and it works well for me.
Use a regular expression.
Quick and dirty attempt:
(?<ID1>[0-9]*)=\[(?<GEN>[a-zA-Z]*)\] OK {Q=(?<Q>[0-9]*) M=(?<M>[0-9]*) B=(?<B>[0-9]*) I=(?<I>[a-zA-Z0-9\-]*)}
This will generate named groups called ID1, GEN, Q, M, B and I.
Check out the MSDN docs for details on using Regular Expressions in C#.
You can use Regex Hero for quick C# regex testing.
You can use String.Split
string[] parts = s.Split(new string[] {"=[", "] ", " {Q=", " M=", " B=", " I=", "}"},
StringSplitOptions.None);
This solution breaks up your report code into segments and stores the desired values into an array.
The regular expression matches one report code segment at a time and stores the appropriate values in the "Parsed Report Code Array".
As your example implied, the first two code segments are treated differently than the ones after that. I made the assumption that it is always the first two segments that are processed differently.
private static string[] ParseReportCode(string reportCode) {
const int FIRST_VALUE_ONLY_SEGMENT = 3;
const int GRP_SEGMENT_NAME = 1;
const int GRP_SEGMENT_VALUE = 2;
Regex reportCodeSegmentPattern = new Regex(#"\s*([^\}\{=\s]+)(?:=\[?([^\s\]\}]+)\]?)?");
Match matchReportCodeSegment = reportCodeSegmentPattern.Match(reportCode);
List<string> parsedCodeSegmentElements = new List<string>();
int segmentCount = 0;
while (matchReportCodeSegment.Success) {
if (++segmentCount < FIRST_VALUE_ONLY_SEGMENT) {
string segmentName = matchReportCodeSegment.Groups[GRP_SEGMENT_NAME].Value;
parsedCodeSegmentElements.Add(segmentName);
}
string segmentValue = matchReportCodeSegment.Groups[GRP_SEGMENT_VALUE].Value;
if (segmentValue.Length > 0) parsedCodeSegmentElements.Add(segmentValue);
matchReportCodeSegment = matchReportCodeSegment.NextMatch();
}
return parsedCodeSegmentElements.ToArray();
}