Reputation: 247
This Code is used to generate New ID based on my last ID. Previously When I generate ID for D0001, D0002 ("^\D+"), etc.... has no Problem But now for C0001,C0002 There is an error Regarding my expression ("^\C+").... Sorry for my English .
string autoquery = "select top(1) CommentID from [Comment] order by CommentID DESC";
SqlCommand cmd1 = new SqlCommand(autoquery, cn);
cn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
dr.Read();
string autoID = dr["CommentID"].ToString();
var prefix = Regex.Match(autoID, "^\\C+").Value;
var number = Regex.Replace(autoID, "^\\C+", "");
var i = int.Parse(number) + 1;
var newString = prefix + i.ToString(new string('0', number.Length));
cn.Close();
Upvotes: 0
Views: 50
Reputation: 18799
Which line does the error occur on?
my guess would be that the error occurs on the line
var prefix = Regex.Match(autoID, "^\\C+").Value;
var number = Regex.Replace(autoID, "^\\C+", "");
because your Regex has found no matches. I would change this to
var prefix = Regex.Match(autoID, "^[A-Za-z]+").Value;
var number = Regex.Replace(autoID, "^[A-Za-z]+", "");
to match all letters a-z in any case rather than just the letter C or D
another way if to defensively code against your regex not finding any matches
var prefix = Regex.Match(autoID, "^\\C+")
if (prefix.Success)
{
var number = Regex.Replace(autoID, "^\\C+", "");
var i = int.Parse(number) + 1;
var newString = prefix + i.ToString(new string('0', number.Length));
}
Upvotes: 1
Reputation: 67968
^C\\d+
You should try this.When you want to match C
you need not escape it.
\\C
can become some special directive like \\d
or \\D
.
Upvotes: 2