我该如何替换一个字符串的一部分,而这部分的起始索引可能是未知的。例如,如果我有以下字符串:
"<sometexthere width='200'>"
"<sometexthere tile='test' width='345'>"
我希望替换宽度属性值,该值可能是未知的,并且如前所述,起始索引也是未知的。
我理解我需要以以下部分为基础进行某种操作,该部分是恒定的,只是我不太明白如何实现。
width='
我该如何替换一个字符串的一部分,而这部分的起始索引可能是未知的。例如,如果我有以下字符串:
"<sometexthere width='200'>"
"<sometexthere tile='test' width='345'>"
我希望替换宽度属性值,该值可能是未知的,并且如前所述,起始索引也是未知的。
我理解我需要以以下部分为基础进行某种操作,该部分是恒定的,只是我不太明白如何实现。
width='
到目前为止,你已经得到了七个错误的答案,告诉你要用正则表达式来完成解析器的工作。请不要使用正则表达式来完成这项任务。我假设你的字符串是一段标记。让我们假设它是HTML。 那么你的正则表达式对以下内容会做什么:
<html>
<script>
var width='100';
</script>
<blah width =
'200'>
... and so on ...
我可以打赌一美元,它替换了 JScript 代码,这是不应该的,也没有替换 blah 标签的属性 - 在属性中有空格是完全合法的。
如果你需要解析一个标记语言,那么请解析标记语言。获取一个解析器并使用它;这就是解析器的作用。
var newString = Regex.Replace(@".*width='\d'",string.Foramt("width='{0}'",newValue));
using System.Text.RegularExpressions;
Regex reg = new Regex(@"width='\d*'");
string newString = reg.Replace(oldString,"width='325'");
如果您在“新宽度”字段的 ' ' 之间放置一个数字,它将返回一个具有新宽度的新字符串。
Regex regex = new Regex(@"\b(width)\b\s*=\s*'d+'");
\b
代表匹配一个完整的词,\s*
代表允许零个或多个空格字符,\d+
表示一个或多个数字占位符。要替换数字值,您可以使用:
int nRepValue = 400;
string strYourXML = "<sometexthere width='200'>";
// 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...
using System.Text.RegularExpressions;
...
string yourString = "<sometexthere width='200'>";
// 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');
我会使用 正则表达式。
类似这样的替换宽度值为123456
。
string aString = "<sometexthere tile='test' width='345'>";
Regex regex = new Regex("(?<part1>.*width=')(?<part2>\\d+)(?<part3>'.*)");
var replacedString = regex.Replace(aString, "${part1}123456${part3}");
你可以使用正则表达式,例如(?<=width=')(\d+)
示例:
var replaced = Regex.Replace("<sometexthere width='200'>", "(?<=width=')(\\d+)", "123");"
replaced
现在是:<sometexthere width='123'>