【问题标题】:RegEx.Replace issue - Custom URL rewriteRegEx.Replace 问题 - 自定义 URL 重写
【发布时间】:2013-03-24 08:05:06
【问题描述】:

我正在尝试编写自己的 301 重定向。我有 2 个字符串。一个是旧网址,另一个是新网址。示例如下

原始网址:

procurement-notice-(\d+).html

新网址:

/Bids/Details/$1

像这样,我有很多新旧网址。我正在执行以下操作以匹配正常工作的 Urls。其中“重定向”是一个包含新旧 url 的字典。

var matchedURL = redirect.SingleOrDefault(d => Regex.Match(url, d.Key, RegexOptions.Singleline).Success);

但现在我想用新的 url 替换匹配的。

【问题讨论】:

    标签: c# regex asp.net-mvc


    【解决方案1】:

    您已匹配 URL,其中 Key - 旧 url 正则表达式和 Value - 新 url 替换模式。

    您可以使用Regex.Replace方法,它接受3个字符串参数。

    using System;
    using System.Text.RegularExpressions;
    
    class App
    {
      static void Main()
      {
        var input = "procurement-notice-1234.html";
        var pattern = @"procurement-notice-(\d+).html";
        var replacement = "/Bids/Details/$1";
        var res = Regex.Replace(input, pattern, replacement);
        Console.WriteLine(res);
        // will output /Bids/Details/1234
      }
    }
    

    因此,在您的情况下,代码可能如下所示:

    var matchedURL = redirect.SingleOrDefault(d => Regex.Match(url, d.Key, RegexOptions.Singleline).Success);
    if (matchedURL != null)
    {
      var result = Regex.Replace(url, matchedURL.Key, matchedURL.Value);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-18
      • 2018-08-14
      • 1970-01-01
      • 2020-09-03
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多