1

我希望在 C# 中将文本作为字符串输入,如BEFORE_PROCESSING标题下所示。该文本的格式需要如下:

  1. 没有任何样式标签的裸句(例如句子1)必须获得样式标签才能使整个句子变为粗体
  2. 需要识别已经有样式标签的句子,并且必须将它们的前景色元素设置为“fg:Red”,以使整个句子看起来是红色的。
  3. 已经有样式标签的句子可能有嵌套的样式标签。所以,这是需要考虑的。

例如,格式化完成后,BEFORE_PROCESSING标题中的句子应该看起来像AFTER_PROCESSING下的文本。

我的问题是在 C# 中实现这种文本处理业务的最有效方法是什么?是使用正则表达式还是矫枉过正?您认为可能存在更好的替代方案吗?谢谢。

(我正在使用 C#4)

BEFORE_PROCESSING

"Sentence 1 <style styles='B;fg:Green'>STYLED SENTENCE</style> Sentence 2"

AFTER_PROCESSING

"<style styles='B'>Sentence 1 </style> 
 <style styles='B;fg:Red'>STYLED  SENTENCE</style>  
 <style styles='B'>Sentence 2</style>"
4

1 回答 1

0

您可以根据正则表达式尝试以下解决方案:

string myLine = "Sentence 1<style styles='B;fg:Green'>STYLED SENTENCE</style>Sentence 2";
const string splitLinesRegex = @"((?<Styled>\<style[^\>]*\>[^\<\>]*\</style\>)|(?<NoStyle>[^\<\>]*))";

var splitLinesMatch = Regex.Matches(myLine, splitLinesRegex, RegexOptions.Compiled);
List<string> styledLinesBis = new List<string>();

foreach (Match item in splitLinesMatch)
{
    if (item.Length > 0)
    {
        if (!string.IsNullOrEmpty(item.Groups["Styled"].Value))
            styledLinesBis.Add(string.Format("<style styles='B'>{0}</style> ", item.Groups["Styled"].Value));

        if (!string.IsNullOrEmpty(item.Groups["NoStyle"].Value))
            styledLinesBis.Add(string.Format("<style styles='B;fg:Red'>{0}</style>  ", item.Groups["NoStyle"].Value));
    }
}

您只需要连接字符串,例如使用 string.Join 语句。

于 2016-07-12T12:38:53.403 回答