0

我有大文本。我需要找到一个 URL 并将找到的文本替换为另一个文本。

这是一个例子:

http://cdn.example.com/content/dev/images/some.png
http://cdn.example.com/content/qa/images/some.png
http://cdn.example.com/content/preprod/images/some.png

http://cdn.example.com/content/qa/images/some.png
http://cdn.example.com/content/preprod/images/some.png
http://cdn.example.com/content/live/images/some.png

我需要找到 url 段并替换找到的段。我有以下代码:

Regex rxCdnReplace = new Regex(@"http://cdn.example.com/content/(\w+)/", RegexOptions.Multiline | RegexOptions.IgnoreCase);
rxCdnReplace.Replace(str,new MatchEvaluator(CdnRename.ReplaceEvaluator))

我怎样才能用正则表达式做到这一点?

4

2 回答 2

2

试试这个正则表达式:

(?<=content\/).+(?=\/images)

它返回 content/ 和 /images 之间的值

例如,对于http://cdn.example.com/content/dev/images/some.png 正则表达式返回的链接dev,您应该替换为qa

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
    // This is the input string we are replacing parts from.
    string input = "http://cdn.example.com/content/dev/images/some.png";

    // Use Regex.Replace to replace the pattern in the input.
      string output = Regex.Replace(input, "(?<=content\/).+(?=\/images)", "qa");

    // Write the output.
    Console.WriteLine(input);
    Console.WriteLine(output);
    }
}
于 2012-08-23T14:41:36.707 回答
1

如果您的字面意思是您需要将这些特定字符串的出现更改为下面显示的字符串,您可以执行以下操作:

str = str.Replace("http://cdn.example.com/content/qa/images/some.png", "http://cdn.example.com/content/preprod/images/some.png")   

但是,我认为这不是您所追求的(正如您提到的正则表达式),所以我认为您需要更具体地了解需要更改的内容。

于 2012-08-23T14:41:07.087 回答