【问题标题】:Multiple bold tags in NSMutableAttributedString with loop?NSMutableAttributedString 中带有循环的多个粗体标签?
【发布时间】:2019-03-26 22:34:30
【问题描述】:

我有一个包含多个标签的字符串,我试图将文本放在粗体中,然后删除粗体标签,如果它只包含一个标签,它就可以正常工作。现在,当字符串包含多个标签时,我试图循环它们,但它只捕获第一个。有人可以指出我在这里做错了什么吗?

string descriptionBody = "This is a <b>text</b> with multiple <b>bold</b> tags";
var content = new NSMutableAttributedString(descriptionBody);

int i = 0;
while (i < Regex.Matches(descriptionBody, "<b>").Count) {
    int start = descriptionBody.IndexOf("<b>", StringComparison.Ordinal);
    int end = descriptionBody.IndexOf("</b>", StringComparison.Ordinal);
    int length = end - start;

    var boldFirst = new NSRange(start, 3);
    var boldLast = new NSRange(end, 4);

    StringExtensions.ParseBoldTags(content, 14, start + 3, length - 3);
    content.Replace(boldLast, string.Empty);
    content.Replace(boldFirst, string.Empty);
    i++;
}

【问题讨论】:

标签: c# ios string xamarin while-loop


【解决方案1】:

每个匹配循环的开始/结束值都相同。您可以使用MatchCollection 的Group 对象来获取匹配的每个索引和长度。

string descriptionBody = "This is a <b>text</b> with multiple <b>bold</b> tags";
var content = new NSMutableAttributedString(descriptionBody);

foreach (Group match in Regex.Matches(descriptionBody, "<b>"))
{
    int start = match.Index;
    int end = match.Index + match.Length;
    var boldEnd = Regex.Matches(descriptionBody.Substring(end), "</b>")[0];
    //~~~
}

更新:

如果您的最终目标是去除粗体标签并创建一个不带任何标记的 NSAttributedString,您可以改用 Regex.Replace:

var strippedStr = Regex.Replace(descriptionBody, "<b>|</b>", "");
var content = new NSAttributedString(strippedStr);

【讨论】:

  • 这段代码只会加粗标签,而不是这些标签内的文本
  • @Jan 你只需要抓住下一个结束粗体匹配,我在我的示例中添加了另一个匹配以提供帮助。
  • 我真的很困惑,哈哈,我想我需要更多的咖啡
  • @Jan 看到我的更新,这就是你想要做的吗?
  • 不行,中间的文字也需要加粗,否则实际上没有意义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
相关资源
最近更新 更多