-1

我有以下字符串示例:

\\servername\Client\Range\Product\

servername、和vales 可以是任何东西,但它们只是代表服务器上的 ta samba 共享ClientRangeProduct

我希望能够采用其中一条路径,并\用一条新路径替换第四条之前的所有内容:例如:

\\10.0.1.1\ITClient\001\0012\ will become:

\\10.0.1.1\Archive\001\0012\

我得到的所有路径都将遵循相同的起始模式\\servername\Client\,使用 C# 如何替换字符串中的所有内容,直到第 4 个“\”?

我看过使用正则表达式,但我一直无法理解它的神奇和力量

4

6 回答 6

2

此正则表达式模式将匹配到第 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
于 2012-09-04T13:21:56.237 回答
1

除非我遗漏了一些重要的东西,否则您可以使用掩码并对其进行格式化:

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);
于 2012-09-04T13:18:37.280 回答
1

您可以使用String.FormatPath.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\
于 2012-09-04T13:19:27.380 回答
1

优雅的正则表达式解决方案是:

(new Regex(@"(?<=[^\\]\\)[^\\]+")).Replace(str, "Archive", 1);

将单个斜杠后面的部分字符串替换为“存档”字符串。

在此处测试此代码。

于 2012-09-04T13:27:48.667 回答
0

字符串方法可以工作,但可能比正则表达式更冗长。如果您想匹配从字符串开头到第 4 个 \ 的所有内容,则以下正则表达式将执行此操作(假设您的字符串符合提供的模式)

^\\\\[^\\]+\\[^\\]+\\

所以一些代码类似于

string updated = Regex.Replace(@"\\10.0.1.1\ITClient\001\0012\", "^\\\\[^\\]+\\[^\\]+\\", @"\\10.0.1.1\Archive\");

应该做的伎俩。

于 2012-09-04T13:25:54.440 回答
0

这个简单快速,只要我们只讨论 4 个部分:

string example = @"\\10.0.1.1\ITClient\001\0012\";
string[] parts = example.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
于 2012-09-04T13:26:27.640 回答