C#替换字符串的一部分

如何替换具有潜在未知起始索引的字符串的一部分。 例如,如果我有以下字符串:

"" "" 

我将寻找替换宽度attibute值,该值可能具有未知值并且如未提及的起始索引之前所述。

我明白我会以某种方式将这个基于以下部分,这是不变的,我只是不太明白如何实现这一点。

 width=' 

 using System.Text.RegularExpressions; Regex reg = new Regex(@"width='\d*'"); string newString = reg.Replace(oldString,"width='325'"); 

如果在新宽度字段中的”之间放置一个数字,这将返回一个具有新宽度的新字符串。

到目前为止,你有7个答案告诉你做错事。 不要使用正则表达式来完成解析器的工作。 我假设你的字符串是一大块标记。 我们假设它是HTML。 你的正则表达式用来做什么:

    ... and so on ... 

我愿意下注多达一美元,它取代了JScript代码,它本不应该,并且不会取代blah标签的属性 – 在属性中包含空格是完全合法的。

如果必须解析标记语言,则解析标记语言 。 给自己一个解析器并使用它; 这就是解析器的用途。

看一下Regex类,您可以搜索属性的内容并使用此类重新生成值。

关闭袖口Regex.Replace可能会做到这一点:

 var newString = Regex.Replace(@".*width='\d'",string.Foramt("width='{0}'",newValue)); 

使用正则表达式

 Regex regex = new Regex(@"\b(width)\b\s*=\s*'d+'"); 

其中\b表示您希望匹配整个单词, \s*允许零个或任意数量的空格字符, \d+允许一个或多个数字占位符。 要替换数值,您可以使用:

 int nRepValue = 400; string strYourXML = ""; // Does the string contain the width? string strNewString = String.Empty; Match match = regex.Match(strYourXML); if (match.Success) strNewString = regex.Replace(strYourXML, String.Format("match='{0}'", nRepValue.ToString())); else // Do something else... 

希望这可以帮助。

您可以使用正则表达式(RegEx)在“width =”之后查找并替换单引号中的所有文本。

你可以使用正则表达式,如(?<=width=')(\d+)

例:

 var replaced = Regex.Replace("", "(?<=width=')(\\d+)", "123");" 

现在replaced为:

我会使用正则表达式 。
这样的东西用123456替换宽度值。

 string aString = ""; Regex regex = new Regex("(?.*width=')(?\\d+)(?'.*)"); var replacedString = regex.Replace(aString, "${part1}123456${part3}"); 

使用正则表达式来实现此目的:

 using System.Text.RegularExpressions; ... string yourString = ""; // updates width value to 300 yourString = Regex.Replace(yourString , "width='[^']+'", width='300'); // replaces width value with height value of 450 yourString = Regex.Replace(yourString , "width='[^']+'", height='450');