在鸿蒙Next中,给定一个字符串‘今天真开心’,‘真’字符实现和其他字符不同颜色,源码https://gitee.com/scenario-samples/regular-highlight,感谢博主

class formatString {
//定义为解析后的标签内容数组,str是要显示的内容,isAim为是否高亮标志
char: string = '';
isAim: boolean = false;
}
@Entry
@Component
struct Index {
@State formatStr: formatString[] = [];
/**
* 主串(待匹配的完整字符串)
*/
@State mainStrInfo: string = '今天真开心';
/**
* 子串(用来匹配的部分)
*/
@State subStrInfo: string = '真';
// 转义特殊字符的函数
escapeRegExp(subStr: string): string {
return subStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
processSource(mainStr: string, subStr: string): formatString[] {
let result: formatString[] = [];
if (mainStr.length === 0 || subStr.length === 0) {
// 如果主串或子串为空,则返回空结果
return result;
}
// 对字串进行转义处理
const escapedSubStr = this.escapeRegExp(subStr);
// 构建正则表达式
const globalMatchRegex = RegExp(escapedSubStr, 'g');
let indexList: number[] = [];
let matchResult: RegExpExecArray | null = null;
// 记录所有匹配位置的索引
while ((matchResult = globalMatchRegex.exec(mainStr)) !== null) {
indexList.push(matchResult.index, globalMatchRegex.lastIndex - 1);
}
let cache = '';
for (let index = 0; index < mainStr.length; index++) {
if (!indexList.includes(index)) {
cache = cache + mainStr[index];
if (index === mainStr.length - 1) {
result.push({ char: cache, isAim: false });
}
} else {
if (cache.length > 0) {
result.push({ char: cache, isAim: false });
cache = '';
}
result.push({ char: subStr, isAim: true })
index = index + subStr.length - 1;
}
}
return result;
}
build() {
Column() {
ForEach(this.processSource(this.mainStrInfo, this.subStrInfo), (item: formatString) => {
if (item.isAim) {
Text(item.char)
.fontSize(20)
.fontColor(Color.Red) //对目标内容进行高亮处理
} else {
Text(item.char)
.fontSize(20);
}
})
}.width('100%').height('100%')
}
}

356

被折叠的 条评论
为什么被折叠?



