How do I parse this string into int fragments?

  • Thread starter Thread starter Top Gun
  • Start date Start date
T

Top Gun

If I have a string that is in a constant format of, say 0154321-001, how can
I parse this into two fragments:

int contractid = 0154321;
int contractseq = 001;
 
If I have a string that is in a constant format of, say 0154321-001, how can
I parse this into two fragments:
int contractid = 0154321;
int contractseq = 001;

You could use the Split method to get two strings (as long as you had a
consistent seperator such as the '-' in your excample) and then convert
those to ints.

Tim
 
If I have a string that is in a constant format of, say 0154321-001, how can
I parse this into two fragments:

int contractid = 0154321;
int contractseq = 001;

string str = "0154321-001";
string[]arr = str.Split('-');
if (arr.Length==2)
{
int contractid = int.Parse(arr[0]);
int contractseq = int.Parse(arr[1]);
}
 
A good idea to use regular expressions for such parsing. Then you don't need to fiddle with the code too much when the syntax of the expression changes (for instance you add another module with "-" and another integer).

The code to parse your syntax would be:

string strRxPattern = "(?<int1>\\d*)-(?<int2>\\d*)";
string strToCheck = "1287103871-87450";
Regex rx = new Regex (strRxPattern);

if (rx.IsMatch (strToCheck))
{
Match mt = rx.Match (strToCheck);
Console.WriteLine (string.Format ("{0}: {1}", "int1", mt.Groups ["int1"].Value));
Console.WriteLine (string.Format ("{0}: {1}", "int2", mt.Groups ["int2"].Value));
}

So, you end up with nicely split strings... :-) Have a good time with regexping! :-)
 
Cezary Nolewajka said:
A good idea to use regular expressions for such parsing. Then you
don't need to fiddle with the code too much when the syntax of the
expression changes (for instance you add another module with "-" and
another integer).

I don't agree with that. Using String.Split, you would only need to
change the check to make sure that it had returned an array with the
appropriate new size, and add the call to parse the final part.

Using a regular expression, you end up with an expression which is
(IMO) harder to read than just a straight call to String.Split, and you
have to change that expression to add a part.

Regular expressions certainly have their place, but to use them when
String.Split works perfectly well is overkill, IMO.
 
Back
Top