1
我試圖在我的文本中找到[Key]
單詞並添加一些內容。Match.index無法正常工作
class Program
{
private string x = "public class Table \n{\n[Key]\r\n[MaxLength(36)]\r\npublic string Char366{ get; set; }\npublic short? Blooean{ get; set; }\n[Key]\r\npublic bool Bit1{ get; set; }\npublic byte? Tinyinttunsigned{ get; set; }\npublic byte[] Binaryy{ get; set; }\npublic byte[] Varbinaryy{ get; set; }\npublic byte[] Blobb{ get; set; }\npublic byte[] Longblobb{ get; set; }\npublic DateTime Datetimee{ get; set; }\npublic decimal Decimall{ get; set; }\npublic double Doublee{ get; set; }\npublic short? Smallintt{ get; set; }\npublic int? Intt{ get; set; }\npublic long Bigintt{ get; set; }\npublic short Tinyintt{ get; set; }\n[Key]\r\npublic float Floatt{ get; set; }\n[MaxLength(1)]\r\npublic string Charr{ get; set; }\n[MaxLength(100)]\r\npublic string Varcharr{ get; set; }\npublic string Textt{ get; set; }\npublic string Longtextt{ get; set; }\npublic TimeSpan Timee{ get; set; }\npublic int? Mediumintt{ get; set; }\npublic long Biggintt{ get; set; }\npublic DateTime Datee{ get; set; }\npublic DateTime Timestampp{ get; set; }\npublic short Yearr{ get; set; }\npublic byte[] Tinyblobb{ get; set; }\npublic string Tinytextt{ get; set; }\npublic byte[] Mediumblobb{ get; set; }\npublic string Mediumtextt{ get; set; }\npublic string Longtexttm{ get; set; }\n[MaxLength(7)]\r\npublic string Enumm{ get; set; }\npublic byte[] Geometryyycol{ get; set; }\npublic byte[] Geometryyy{ get; set; }\n}";
private void method()
{
var wordToFind = @"\[(Key)\]";
var occurrences = Regex.Matches(x,wordToFind);
var timesOfOccurrences = 0;
foreach (Match m in occurrences)
{
timesOfOccurrences++;
x = x.Insert(m.Index + m.Length-1, string.Format(",Order={0}", timesOfOccurrences));
}
Console.WriteLine(x);
Console.ReadLine();
}
它只適用於第一次出現的單詞。我的正則表達式有什麼問題嗎?結果如下:
謝謝,工作正常。 – TjDillashaw
我也提供了代碼在開始時失敗的原因。由於您正在修改輸入字符串,因此所有索引都會移位。這就是爲什麼在比賽評估者中進行替換更安全的原因。 –