string[] src = { "AC1234", "GS3R2C1234", "1234", "A-1234", "AC1234g",
"GS3R2C1234g", "1234g", "A-1234g", "999", "GS3R2C9999g" };
foreach (string before in src)
{
string after = Regex.Replace(before, @"\d+(?=\D*$)",
m => (Convert.ToInt64(m.Value) + 1).ToString());
Console.WriteLine("{0} -> {1}", before, after);
}
输出:
AC1234 -> AC1235
GS3R2C1234 -> GS3R2C1235
1234 -> 1235
A-1234 -> A-1235
AC1234g -> AC1235g
GS3R2C1234g -> GS3R2C1235g
1234g -> 1235g
A-1234g -> A-1235g
999 -> 1000
GS3R2C9999g -> GS3R2C10000g
笔记:
@LB 使用 lambda 表达式作为 MatchEvaluator FTW!
从@spender 的回答来看,前瞻 - (?=\D*$)
- 确保只有最后一组数字匹配(但后瞻 - (?<=(\D|^))
- 不需要)。
@JeffMoser 使用的 RightToLeft 选项允许它首先匹配最后一组数字,但没有静态Replace
方法允许您 (1) 指定 RegexOptions,(2) 使用 MatchEvaluator,以及 (3) 限制替换的数量. 您必须先实例化一个 Regex 对象:
string[] src = { "AC1234", "GS3R2C1234", "1234", "A-1234", "AC1234g",
"GS3R2C1234g", "1234g", "A-1234g", "999", "GS3R2C9999g" };
foreach (string before in src)
{
Regex r = new Regex(@"\d+", RegexOptions.RightToLeft);
string after = r.Replace(before, m => (Convert.ToInt64(m.Value) + 1).ToString(), 1);
Console.WriteLine("{0} -> {1}", before, after);
}
输出:
AC1234 -> AC1235
GS3R2C1234 -> GS3R2C1235
1234 -> 1235
A-1234 -> A-1235
AC1234g -> AC1235g
GS3R2C1234g -> GS3R2C1235g
1234g -> 1235g
A-1234g -> A-1235g
999 -> 1000
GS3R2C9999g -> GS3R2C10000g