簡體   English   中英

C#用單個字符替換字符串中的數字組

[英]C# Replace group of numbers in a string with a single character

有人知道我可以用一個*代替字符串中的一組數字。 例如,如果我有一個類似“ Test123456.txt”的字符串,我想將其轉換為“ Test#.txt”。 我看過很多例子,可以用一個新字符替換每個數字,但沒有一個例子可以處理一組數字。 任何幫助深表感謝!

Regex r = new Regex(@"\d+", RegexOptions.None);
            Console.WriteLine(r.Replace("Test123456.txt", "#"));
            Console.Read();

您可以使用正則表達式來執行此操作,但是如果您知道確切的文本,則使用string.Replace方法會更有效:

string str =  "blahblahblahTest123456.txt";
str = string.Replace("Test#.txt","Test123456.txt");

使用Regex.Replace()如下:

string fileName = "Test12345.txt";
string newFileName = Regex.Replace(fileName, @"[\d]+", "#");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM