2012-03-07 114 views
3

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

"<sometexthere width='200'>" 
"<sometexthere tile='test' width='345'>" 

我会寻找替代,可以有一个未知值和未知的开始索引之前提到的宽度attibute值。

我明白,我将不知何故必须将此基于以下部分,这是恒定的,我只是不太明白如何实现这一点。

width=' 
+3

这看起来像一个工作...... [正则表达式](http://www.regular-expressions.info/examples.html)! – jrummell 2012-03-07 21:08:28

+3

+1找到创造性的方式来绕过“如何用RegEx解析HTML”和“我想用字符串操作解析和构造XML”的标准答案。 – 2012-03-07 21:17:20

+11

@jrummell:这看起来像一个解析器的工作。这看起来不像正则表达式的工作。首先,正则表达式不考虑标记的语法,其次*迄今发布的每个正则表达式都是错误的*。 – 2012-03-07 21:51:41

回答

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

这将返回一个新宽度的字符串,只要您在新宽度字段中的“'之间放置一个数字即可。

+0

干净的解决方案Jetti,谢谢你。 +1 – 2012-03-07 21:20:44

+0

@RyanSmith很高兴能帮到你! – Jetti 2012-03-07 21:27:17

4

看看在Regex类,你可以搜索属性的内容和repalce这一类的价值。

即兴Regex.Replace可能做的伎俩:

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

请参阅:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Khan 2012-03-07 21:09:20

0

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

0

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

例子:

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

replaced现在是:<sometexthere width='123'>

0

使用正则表达式来实现这一目标:

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'); 
+0

假设宽度属性始终是数值。不一定是有效的假设。 – 2012-03-07 21:13:05

0

我会使用Regex
像这样用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}"); 
2

使用正则表达式

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

其中\b小号表明,要匹配整个字,\s*允许零或任意数量的空格charaters和\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... 

希望这有助于。

+0

为什么*一个*空格字符? ** XML允许无限空白**。 – 2012-03-07 21:49:52

+0

修正 - 我不知道为什么我这样做:]。谢谢。 – MoonKnight 2012-03-08 00:37:16

35

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

<html> 
<script> 
    var width='100'; 
</script> 
<blah width = 
       '200'> 
... and so on ... 

我愿意打赌不亚于它所替代的JScript代码,一块钱,它不应该,也不会取代嗒嗒标签的属性 - - 在属性中有空格是完全合法的。

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

+0

+1。这个。 (更多人物) – Rob 2012-03-08 06:40:35

+0

我很高兴有人提到这个。当我读到其他答案时,我想到了完全一样的东西。 – 2012-03-10 19:44:09