您不一定需要正则表达式,但您可以调整您的\((?<number>\d+)\)$
以解决问题。
对于正则表达式解决方案,您可以使用组访问匹配项:
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);
}
相反,考虑只使用 IndexOf 和 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);
}
生产
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)