C # Regex replace help

I have a line:

Apple1231 | C: \ asfae \ drqw \ Qwer | 2342 | 1.txt

I have the following code:

 Regex line2parse = Regex.Match(line,@"(\|)(\|)(\|)(\d)");
 if (line2parse < 2)
 {

     File.AppendAllText(workingdirform2 + "configuration.txt",

What I want to do is to replace each |after the first |with \ So I want to write

Apple1231 | C: \ asfae \ drqw \ Qwer \ 2342 \ 1.txt

+5
source share
8 answers

+1 John. Obviously, regular expressions are not the best solution here, but here I take:

string original = @"Apple1231|C:\asfae\drqw\qwer|2342|1.txt";
Regex pattern = new Regex(@"(?<=.*\|)(?'rep'[^\|]*)\|");
string result = pattern.Replace(original, @"${rep}\");

This is more general than strictly necessary because it will handle an arbitrary number of replacements.

+1
source

You can do this without regex:

string line = @"Apple1231|C:\asfae\drqw\qwer|2342|1.txt";
string[] parts = line.Split('|');
string clean = parts[0] + "|" + string.Join(@"\", parts, 1, parts.Length - 1);

string.Join , , .

+9

Regex, IndexOf(), "|", .Substring() 1 ... , , , ☺

+4

:

var result = Regex.Replace( line, @"(.+?)\|(.+?)\|(.+?)\|(.+?)", "$1|$2\\$3\\$4");
0

,

fixed = Regex.Replace(unfixed.replace("|", @"\"), @"\\", "|", 1);

, , .

0

.

        string input = @"Apple1231|C:\asfae\drqw\qwer|2342|1.txt";
        int firstPipeIndex = input.IndexOf("|");
        string suffix = string.Empty;
        string prefix = string.Empty;
        string output = string.Empty;
        if (firstPipeIndex != -1)
        {
            //keep the first pipe and anything before in prefix
            prefix = input.Substring(0, firstPipeIndex + 1);
            //all pipes in the rest of it should be slashes
            suffix = input.Substring(firstPipeIndex + 1).Replace('|', '\\');
            output = prefix + suffix;
        }
        if (!string.IsNullOrEmpty(suffix))
        {
            Console.WriteLine(input);
            Console.WriteLine(output);
        }
0

, :

Regex MyRegex = new Regex(
      @"(.+\|)(.+)\|(\d{1,})\|(.+)",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );


// This is the replacement string
string MyRegexReplace = 
      @"$1$2\$3\$4";


//// Replace the matched text in the InputText using the replacement pattern
string result = MyRegex.Replace(@"Apple1231|C:\asfae\drqw\qwer|2342|1.txt",MyRegexReplace);
//
result 'Apple1231|C:\asfae\drqw\qwer\2342\1.txt'

, , , .

0

, N , .

static string FixString(string line)
{
    if (line == null)
        return string.Empty;

    int firstBarPosition = line.IndexOf('|');
    if (firstBarPosition == -1 || firstBarPosition + 1 == line.Length)
        return line;

    StringBuilder sb = new StringBuilder(line);

    sb.Replace('|', '\\', firstBarPosition + 1, line.Length - (firstBarPosition + 1));
    return sb.ToString();
}
0

All Articles