2014-09-22 26 views
2

Ich在多行文本中显示c#中的正则表达式替换函数时出现问题。在这个文本中,我有不同的行有时与特殊字符(例如:&和& &)在一开始行必须转换例如。 HTML。这是作为一个降价的转换类似...Regex.replace将不会替换多行文本行以开始字符到html块

一个例子如下文字:

This is a normal demo text. 
&Here an other demo text. 
And one more demo text. 
&&Here will continue this text. 
Bla bla blaaa... 

文本应替换为在与开始和结束HTML标记文本后:

This is a normal demo text. 
<b>Here an other demo text.</b> 
And one more demo text. 
<em>Here will continue this text...</em> 
Bla bla blaaa... 

对于替换&和& &我创建了以下c#代码:

private string StartConvert(str text) 
{ 
text = Regex.Replace(text, "^[&]{1}((?![&]).+)$", "<b>$1</b>", RegexOptions.Multiline); 
text = Regex.Replace(text, "^[&]{2}((?![&]).+)$", "<em>$1</em>", RegexOptions.Multiline); 
} 

运行,我会得到错误以下后:

This is a normal demo text. 
</b>ere an other demo text. 
And one more demo text. 
</em>ere will continue this text... 
Bla bla blaaa... 

为什么这工作不正常,为什么我行的前面拿到,只有关闭标签。如果它是一个单独的行,它可以正常工作,但不是多行。

感谢您的帮助

+0

如何分配的输入? – 2014-09-22 07:08:55

+0

我也测试了这个,Regex在正则表达式制造商中工作正常,但是当涉及到C#时,它跳过H – Charlie 2014-09-22 07:22:52

+0

您的代码适用于我http://ideone.com/XhQzoR – 2014-09-22 07:37:20

回答

0

我假设你的文件是Windows EOF编码:\r\n

表达式:"^[&]{1}((?![&]).+)$"将匹配&Here an other demo text.\r\n

后面的参考((?![&]).+)将是Here an other demo text.\r

有了这个替换字符串:<b>Here an other demo text.\r</b>

<b>Here an other demo text.\r 
^___________________________| 

CR \r光标返回到该行的开头。

</b>ere an other demo text.\r 
|__^ 

重写<b>H</b>

0

这不是解决办法,但我可以告诉你,这个问题是不是在正则表达式,问题出在打印文本。我看到了结果字符串是完全正常 所以我做了这样的事情来检查它

 string[] strings = text.Split(' '); 

     foreach (var s in xa) 
     { 
      Console.WriteLine(s); 

     } 

你可以检查字符串,而调试,这是好的?

相关问题