Reputation: 490
I have a simple solution for a small problem, but as a newbie developer, I always want to learn the more correct/better ways to do something. At the moment, I get a string that looks more or less like this...
Some Random Text, Reference Number: Supp-1234 and some more random text...
Now if we assume this scenario and we want to get only the digit part of the reference number, we can do something like this...
int firstCharacter = mystring.IndexOf("Supp-", StringComparison.InvariantCultureIgnoreCase);
myIssueId = firstCharacter != -1 ? mailItem.Subject.Substring(firstCharacter + 5, 4) : "";
But now, suppose we get a reference number Supp-12345, now this wont work. You can try something like this...
int firstCharacter = mystring.IndexOf("Supp-", StringComparison.InvariantCultureIgnoreCase);
if (firstCharacter != -1)
{
string temp = mystring.Substring(firstCharacter + 5, 5);
try
{
int x = Convert.ToInt32(temp); // to ensure it is indeed a number
}
catch (Exception)
{
temp = mystring.Substring(firstCharacter + 5, 4); // it is 4 digits, not 5
}
myIssueId = temp;
}
Now my question is this. How do I improve this code? Its a bit too messy for my liking. Any ideas will be appreciated.
Upvotes: 3
Views: 285
Reputation: 25593
Your are looking for some digits that are preceeded by the string "Supp-". This can be translated into a regular expression like
(<=Supp-)\d+
You'd use it like myIssueId = Regex.Match(input, "(<=Supp-)\d+").Value
.
Upvotes: 3