我发现了有关如何增加一个字符串的解释,该字符串首先包含字母的一部分,然后是数字的一部分,如下所示:
ASD0001 => ASD0002 => ASD0003
我正在寻找的是一小段代码,该代码可以执行以下操作:
123ASD0001 => 123ASD0002 => 123ASD0003
Increment a string with both letters and numbers中的示例以及类似的问题似乎是基于这样的情况,即只有几个字母后跟几个数字,但是我需要一种更自由地执行此操作的方法。
答案 0 :(得分:0)
在正则表达式中使用IEnumerator
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Increment increment = new Increment("ASD0001");
for (int i = 0; i < 10; i++ )
{
Console.WriteLine(increment.Current);
increment.MoveNext();
}
Console.ReadLine();
}
}
public class Increment : IEnumerator<string>
{
string prefix = "";
int numberDigits = 0;
int? _current = null;
public Increment(string numStr)
{
string pattern = @"(?'prefix'.*)(?'digits'\d+)";
Match match = Regex.Match(numStr, pattern, RegexOptions.RightToLeft);
prefix = match.Groups["prefix"].Value;
string digits = match.Groups["digits"].Value;
_current = int.Parse(digits);
numberDigits = digits.Length;
}
object IEnumerator.Current
{
get { return this.Current; }
}
public string Current
{
get {
if (_current == null)
{
return "";
}
else
{
return prefix + new string('0', numberDigits - _current.ToString().Length) + _current.ToString();
}
}
}
public bool MoveNext()
{
if (_current == null)
return false;
_current += 1;
return true;
}
public void Reset()
{
prefix = "";
numberDigits = 0;
_current = null;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
}