如何在文本中加粗字符串

本文关键字:字符串 文本 | 更新日期: 2023-09-27 18:10:35

我的问题和这个类似https://stackoverflow.com/questions/18944437/replacing-text-between-b-and-b-with-bold-text-in-c-sharp

我想在<*strong>标签之间加粗字符串

我得到了带有 的字符串
string pattern = @"<strong>(.*?)</strong>";
var matches = Regex.Matches(paragraf2.Range.Text, pattern)
                   .Cast<Match>()
                   .Select(m => m.Groups[1].Value)
                   .ToList();

我想我需要一些像

foreach( string a in matches)
{     
}

但是我不知道里面该写些什么

如何在文本中加粗字符串

根据您的情况(如果描述正确),您可以通过修改字符串来使用[https://stackoverflow.com/questions/18944437/replacing-text-between-b-and-b-with-bold-text-in-c-sharp]中给出的解决方案:

 richTextBox1.SelectedText = richTextBox1.SelectedText.Replace("<b>", "").Replace("</b>", "");

如下所示:

richTextBox1.SelectedText = richTextBox1.SelectedText.Replace("<strong>", String.Empty).Replace("</strong>", String.Empty);

或者,相应的解决方案(修改后的原件)如下:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    string regexString = "(?<=<strong>)(.*?)(?=</strong>)";
    Match matches = (Regex.Match(richTextBox1.Text, regexString));
    if (matches.Success)
    {
        int index1 = richTextBox1.Find("<strong>");
        int index2 = richTextBox1.Find("</strong>");
        richTextBox1.Select(index1 + 3, ((index2) - (index1 + 3)));
        richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size, FontStyle.Bold);
    }
}

有关RichTextBox字体属性的更多详细信息,请参阅以下代码片段(来自Microsoft文档online http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.selectionfont%28v=vs.100%29.aspx):

private void ToggleBold()
{
   if (richTextBox1.SelectionFont != null)
   {
      System.Drawing.Font currentFont = richTextBox1.SelectionFont;
      System.Drawing.FontStyle newFontStyle;
      if (richTextBox1.SelectionFont.Bold == true)
      {
         newFontStyle = FontStyle.Regular;
      }
      else
      {
         newFontStyle = FontStyle.Bold;
      }
      richTextBox1.SelectionFont = new Font(
         currentFont.FontFamily, 
         currentFont.Size, 
         newFontStyle
      );
   }
}

Rgds,

正如har07在评论中所说,你可以像

       string pattern = @"<strong>(.*?)</strong>";
       var matches = Regex.Matches(paragraf2.Range.Text, pattern)
               .Cast<Match>()
               .Select(m => m.Groups[1].Value)
               .ToList();
       Word.Find findObject = Application.Selection.Find;
       foreach( string a in matches){ 
            findObject.ClearFormatting();
            findObject.Text = a;
            findObject.Replacement.ClearFormatting();
            findObject.Replacement.Font.Bold = 1;
            object replaceAll = Word.WdReplace.wdReplaceAll;
            findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);  
           }