krishna mohan
krishna mohan

Reputation: 921

how to extrct particular string from string and increment that in c# using regex

i have created one id - i want to increment that id . for that i need to replace the string in a string

input string - KST-HYD/15-116/001/CST

i extracted 001, but im unable to replace 001 with 002

code behind

 Regex regex = new Regex(@"\/(\d+)\/");
Match match = regex.Match(txtId.Text.Trim());
if (match.Success)
{
    //Console.WriteLine(match.Value);
    int oldid = Convert.ToInt32(match.Groups[1].Value);
    int newid = oldid + 1;
    string newidstring = newid.ToString();
    string idformat = "KST-HYD/15-116/@/CST";
    StringBuilder builder = new StringBuilder(idformat);
    builder.Replace("@",newidstring);
    string newGeneratedId = builder.ToString();
    Response.Write(newGeneratedId);

}

Upvotes: 3

Views: 131

Answers (3)

Ian
Ian

Reputation: 30813

Use string.Remove, string.Insert, and Convert.ToInt32:

string txt = match.Groups[1].Value;
int pos = match.Index; //please add this for getting the position for the match
txtId.Text = txtId.Text.Remove(pos + 1, txt.Length).Insert(pos + 1, (Convert.ToInt32(txt) + 1).ToString("d3"));

Edit: Thanks for correction from Mr. Giorgi and others. I updated the answer to position-based.

Upvotes: 2

fubo
fubo

Reputation: 45987

here is a one liner solution

string txtId = "KST-HYD/15-116/001/CST";            
string result = Regex.Replace(txtId, @"(?<=\/)\d{3}(?=\/)", s => (int.Parse(s.Value)+1).ToString("d3"));

UPDATE: RegEx:

(?<=\/) number starts with / but it's not a part of the number

\d{3} the number has always a fix length of 3

(?=\/) number ends with / but it's not a part of the number

Upvotes: 2

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

Here is how I would do this to replace exactly at the position where match is found:

var t = "KST-HYD/15-116/001/CST";
Regex regex = new Regex(@"\/(?<m>\d+)\/");
Match match = regex.Match(t);

if (match.Success)
{
    string txt = match.Groups["m"].Value;
    var pos = match.Index;
    var vali = int.Parse(txt);

    var sb = new StringBuilder(t);
    sb.Remove(pos + 1, txt.Length);
    sb.Insert(pos + 1, (++vali).ToString("000"));

    t = sb.ToString();
}

Upvotes: 1

Related Questions