[英]Multiple bold tags in NSMutableAttributedString with 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++;
}
每个匹配循环的开始/结束值都相同。 您可以使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.