C#Regex替换帮助

时间:2010-01-21 20:37:40

标签: c# regex

我有一个字符串:

  

Apple1231 | C:\ asfae \ drqw \ QWER | 2342 |的1.txt

我有以下代码:

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

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

我希望能够做到的是在第一个|之后用|替换每个\ 所以我想写出来

  

Apple1231 | C:\ asfae \ drqw \ QWER \ 2342 \ 1.txt的

8 个答案:

答案 0 :(得分:9)

你可以在没有正则表达式的情况下做到这一点:

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调用使用一个重载,允许您指定一个开始索引来跳过第一个项目。

答案 1 :(得分:4)

我不会使用正则表达式,但是IndexOf()首先找到“|”,然后从该位置加上.Substring()加1直到结束...先验,它应该表现更好 - 但是总是伴随着表演,现实惊喜☺

答案 2 :(得分:1)

+1约翰。 显然正则表达式不是最好的解决方案,但这是我的看法:

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

这比非常必要的更通用,因为它将处理任意数量的替换。

答案 3 :(得分:0)

因为你要求使用正则表达式:

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

答案 4 :(得分:0)

完全未经测试,但请尝试

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

即将所有条形图变为斜线,然后将第一条斜线转回条形图。

答案 5 :(得分: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);
        }

答案 6 :(得分: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'

希望这有帮助, 最好的祝福, 汤姆。

答案 7 :(得分: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();
}