NSMutableAttributedString中的多个粗体标签带有循环?

时间:2018-10-22 19:15:19

标签: c# ios string xamarin while-loop

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

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++;
}

1 个答案:

答案 0 :(得分:0)

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

MatchCollection

更新:

如果您的最终目标是剥离粗体标签并创建一个没有任何标记的NSAttributedString,则可以使用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]; //~~~ } 代替:

Regex.Replace