《鸿蒙开发-答案之书》拆分文本里的链接和普通文本
/**
* @desc : 拆分文本里的链接和普通文本。子数组第一位是标识:link是链接;text是文本。子数组第二位是内容
**/
export function extractLinksAndTexts(input: string): string[][] {
let matches = input.matchAll(new RegExp(/(?<text>[^(http)]+)|(?<link>https?:\/\/[-\w+&@#/%?=~_|!:,.;]+[-\w+&@#/%=~_|])/g))
let result: string[][] = []
// 遍历所有匹配项,将链接和文本添加到结果数组中。子数组第一位是标识:link是链接;text是文本。子数组第二位是内容
for (let match of matches) {
if (match.groups){
if (match.groups.link) {
result.push(['link',match.groups.link])
} else if (match.groups.text) {
result.push(['text',match.groups.text])
}
}
}
return result
}