用大字符串替换所有regEx匹配 [英] replacing all regEx matches in large string

查看:84
本文介绍了用大字符串替换所有regEx匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的我有以下代码,但是当它运行时它不会返回被替换的字符串;



  private   string  ReplaceDescription( string  description)
{
var newDescription = description.Replace( / en / products / purpose / / en /);
return newDescription;
}

private string ReplaceProductDescription( string description)
{
string pattern = @ / en / products / \d {4} / \d {4} \.aspx;
Regex regEx = new 正则表达式(模式);
foreach (匹配匹配 regEx.Matches(description))
{
string matchedValue = match.Value;
string productNumber = System.IO.Path.GetFileNameWithoutExtension(matchedValue);
description.Replace(matchedValue, newString);
}
返回说明;

}





第一种方法工作正常,但第二种方法不会返回带有替换的描述,任何非常感谢帮助。

解决方案

为什么不让正则表达式做替换呢?

  private   string  ReplaceProductDescription( string  description)
{
string pattern = @ / EN /产品/(小于?PN1> \d {4})/(< PN2> \d {4})\.aspx;
Regex regEx = new 正则表达式(模式);
return regEx.Replace(description, newString pn1 here:


{pn1} pn2 here:


{pn2});
}



您可能想要预构建 Regex 一次,而不是每次调用


Ok i have the following code, but when it runs it doesn't return the replaced string;

private string ReplaceDescription(string description)
       {
           var newDescription = description.Replace("/en/products/purpose/", "/en/");
           return newDescription;
       }

       private string ReplaceProductDescription(string description)
       {
           string pattern = @"/en/products/\d{4}/\d{4}\.aspx";
           Regex regEx = new Regex(pattern);
           foreach (Match match in regEx.Matches(description))
           {
               string matchedValue = match.Value;
               string productNumber = System.IO.Path.GetFileNameWithoutExtension(matchedValue);
               description.Replace(matchedValue, "newString");
           }
           return description;

       }



The first method works fine, but the second one wont return the description with replacements, any help would be great many thanks.

解决方案

Why not just have the Regex do the replacement?

private string ReplaceProductDescription(string description)
{
    string pattern = @"/en/products/(?<pn1>\d{4})/(?<pn2>\d{4})\.aspx";
    Regex regEx = new Regex(pattern);
    return regEx.Replace(description, "newString pn1 here:


{pn1} pn2 here:


{pn2}"); }


And you probably want to pre-construct the Regex once, instead of on each call.


这篇关于用大字符串替换所有regEx匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆