简体   繁体   中英

Capturing a number within curly brackets inside a string c#

I have posted this again as my previous post was admittedly rather ambiguous..sorry!!

I have a string and I want to capture the number inside it and then add one to it!.

For example I have an email subject header saying "Re: Hello (1)"

I want to capture that 1 and then raise it by 2, then 3,then 4,etc. The difficulty I am having is taking into consideration the growing numbers, once it becomes say 10 or 100, that extra digit kills my current Regex expression.

Any help would be praised as always!

     int replyno;
     string Subject = "Re: Hey :) (1)";
     if (Subject.Contains("Re:"))
     {
         try
         {
             replyno = int.Parse(Regex.Match(Subject, @"\(\d+\)").Value);
             replyno++;
             Subject = Subject.Remove(Subject.Length - 3);
             TextBoxSubject.Text = Subject + "("+replyno+")";
         }
         catch
         {
             TextBoxSubject.Text = Subject + " (1)";
         }

     }
     else
     {
         TextBoxSubject.Text = "Re: " + Subject;
     }

Current output from this code fails from the Int.TryParse

Try substituting this code:

var m = Regex.Match(Subject, @"\((\d+)\)");
replyno = int.Parse(m.Groups[1].Value);

The changes are:

  • capture just the digits in the regex
  • parse just the captured digits

I'd also recommend that you check m.Success instead of just catching the resulting exception.

I don't normally deal with regex so here's how i'd do it.

string subject = "Hello (1)";
string newSubject = string.Empty;

for (int j = 0; j < subject.Length; j++)
    if (char.IsNumber(subject[j]))
         newSubject += subject[j];

int number = 0;

 int.TryParse(newSubject, out number);
 subject = subject.Replace(number.ToString(), (++number).ToString());

You don't necessarily need regex for this, but you can adjust yours to \\((?<number>\\d+)\\)$ to fix the problem.

For a regex solution, you can access the match using a group:

for (int i = 0; i < 10; i++)
{
  int currentLevel = 0;
  var regex = new System.Text.RegularExpressions.Regex(@"\((?<number>\d+)\)$");

  var m = regex.Match(inputText);
  string strLeft = inputText + " (", strRight = ")";
  if (m.Success)
  {
    var levelText = m.Groups["number"];
    if (int.TryParse(levelText.Value, out currentLevel))
    {
      var numCap = levelText.Captures[0];

      strLeft = inputText.Substring(0, numCap.Index);
      strRight = inputText.Substring(numCap.Index + numCap.Length);
    }
  }

  inputText = strLeft + (++currentLevel).ToString() + strRight;

  output.AppendLine(inputText);
}

Instead, consider just using IndexOf and Substring:

// Example
var inputText = "Subject Line";

for (int i = 0; i < 10; i++)
{
  int currentLevel = 0;
  int trimStart = inputText.Length;

  // find the current level from the string
  {
    int parenStart = 0;
    if (inputText.EndsWith(")")
        && (parenStart = inputText.LastIndexOf('(')) > 0)
    {
      int numStrLen = inputText.Length - parenStart - 2;
      if (numStrLen > 0)
      {
        var numberText = inputText.Substring(parenStart + 1, numStrLen);
        if (int.TryParse(numberText, out currentLevel))
        {
          // we found a number, remove it
          trimStart = parenStart;
        }
      }
    }
  }

  // add new number
  {
    // remove existing
    inputText = inputText.Substring(0, trimStart);

    // increment and add new
    inputText = string.Format("{0} ({1})", inputText, ++currentLevel);
  }

  Console.WriteLine(inputText);
}

Produces

Subject Line
Subject Line (1) 
Subject Line (2) 
Subject Line (3) 
Subject Line (4) 
Subject Line (5) 
Subject Line (6) 
Subject Line (7) 
Subject Line (8) 
Subject Line (9) 
Subject Line (10) 

The problem is with the way you remove and replace the reply no.

Change your code this way

int replyno;
     string Subject = "Re: Hey :) (1)";
     if (Subject.Contains("Re:"))
     {
         try
         {
             replyno = int.Parse(Regex.Match(Subject, @"(\d+)").Value);
             replyno++;
             Subject = Regex.Replace(Subject,@"(\d+)", replyno.ToString());
             TextBoxSubject.Text = Subject ;
         }
         catch
         {
             TextBoxSubject.Text = Subject + " (1)";
         }

     }
     else
     {
         TextBoxSubject.Text = "Re: " + Subject;
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM