[英]How to replace first part of a string with a given pattern in C#
我有以下字符串示例:
\\servername\Client\Range\Product\
servername
, Client
, Range
和Product
值可以是任何值,但是它們只是表示服務器上的samba共享。
我希望能夠采用這些路徑之一,並使用新路徑使所有內容都恢復到第四個\\
:
\\10.0.1.1\ITClient\001\0012\ will become:
\\10.0.1.1\Archive\001\0012\
我得到的所有路徑都將遵循相同的開始模式\\\\servername\\Client\\
,使用C#如何將字符串中的所有內容替換為第4個“ \\”?
我已經看過使用正則表達式,但是我從未能夠理解它的奇跡和力量
此正則表達式模式將匹配到第4個\\
^(?:.*?\\){4}
用法:
var result = Regex.Replace(inputString, @"^(?:.*?\\){4}", @"\\10.0.1.1\Archive\");
為了闡明正則表達式:
^ // denotes start of line
(?:…) // we need to group some stuff, so we use parens, and ?: denotes that we do not want to use the parens for capturing (this is a performance optimization)
.*? // denotes any character, zero or more times, until what follows (\)
\\ //denotes a backslash (the backslash is also escape char)
{4} // repeat 4 times
除非我缺少主要的東西,否則您可以使用遮罩並將其格式化:
static string pathMask = @"\\{0}\{1}\{2}\{3}\";
string server = "10.0.1.1";
string client = "archive";
string range = "001";
string product = "0012";
...
string path = string.Format(pathMask, server, client, range, product);
您可以使用String.Format
或Path.Combine
string template = @"\\{0}\{1}\{2}\{3}\";
string server = "10.0.1.1";
string folder = "Archive";
string range = "001";
string product = "0012";
string s1 = String.Format(template,
server,
folder,
range,
product);
// s1 = \\10.0.1.1\Archive\001\0012\
string s2 = Path.Combine(@"\\", server, folder, range, product);
// s2 = \\10.0.1.1\Archive\001\0012\
優雅的正則表達式解決方案是:
(new Regex(@"(?<=[^\\]\\)[^\\]+")).Replace(str, "Archive", 1);
它取代“歸檔”字符串中的一個斜線后面的字符串的一部分。
字符串方法可以工作,但比正則表達式更冗長。 如果要匹配從字符串開頭到第4個\\的所有內容,則以下正則表達式將執行此操作(假設您的字符串符合提供的模式)
^\\\\[^\\]+\\[^\\]+\\
所以一些類似的代碼
string updated = Regex.Replace(@"\\10.0.1.1\ITClient\001\0012\", "^\\\\[^\\]+\\[^\\]+\\", @"\\10.0.1.1\Archive\");
應該做到的。
只要我們只談論四個部分,這一步既簡單又快速。
string example = @"\\10.0.1.1\ITClient\001\0012\";
string[] parts = example.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.