简体   繁体   中英

C# Remove Part of a String with only knowledge of start and end of the part

This is actual example of what I want to accomplish:

I have this string :

File Name="Unstuck20140608124131432.txt" Path="Unstuck20140608124131432.txt" Status="Passed" Duration="0.44"

And i want to cut the "Path" attribute from it, so it will look like this:

File Name="Unstuck20140608124131432.txt" Status="Passed" Duration="0.44"

I don't know nothing about the length of the path or the characters inside the " " of the path.

How can i accomplish it ?

You can use Regex.Replace

string input = @"File Name=""Unstuck20140608124131432.txt"" Path=""Unstuck20140608124131432.txt"" Status=""Passed"" Duration=""0.44""";
var output = Regex.Replace(input, @"Path=\"".+?\""", "");

And for you non-regex fans out there, you can use the split command. (Nothing against regex. It is an important part of a balanced programmer diet.)

var input = "File Name=\"Unstuck20140608124131432.txt\" Path=\"Unstuck20140608124131432.txt\" Status=\"Passed\" Duration=\"0.44\"";

var tmp = input.Split(new[] { "Path=\"" }, 2, StringSplitOptions.None);

var result = tmp[0] + tmp[1].Split(new[] { '"' }, 2)[1];

Split the string into 2 parts based on the start of your pattern (Path="). Take the first part. Split the 2nd part into 2 parts based on the end of the pattern ("). Take the 2nd part of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM