Flutter中如何用正则表达式拆分含HTML标签的字符串列表?
用正则表达式拆分含
<a>标签的句子为指定数组 核心思路
我们需要把目标句子拆分成普通文本片段和完整的<a>标签片段交替的数组,核心是用正则同时匹配这两类内容,再过滤掉无效的空片段。
正则表达式说明
使用以下正则进行全局匹配:
/(<a\s+[^>]+>.*?<\/a>)|([^<>]+)/g
<a\s+[^>]+>.*?<\/a>:匹配完整的<a>标签,包含所有属性和标签内文本(非贪婪匹配避免跨标签匹配)[^<>]+:匹配不在标签内的普通文本(即所有非<、>的字符)|:交替匹配两种类型的片段g:全局匹配,找出所有符合条件的片段
实现步骤(以JavaScript为例)
- 对每一行目标句子执行正则匹配,提取所有片段
- 过滤掉空字符串或纯空白的无效片段
- 对每个有效片段去除首尾空白,最后拼接成指定的数组格式
示例代码:
// 处理单句的工具函数 function splitSentence(str) { // 匹配所有标签和文本片段 const matches = str.match(/(<a\s+[^>]+>.*?<\/a>)|([^<>]+)/g); // 过滤空片段并去除首尾空白 const filteredParts = matches.filter(part => part.trim() !== '').map(part => part.trim()); // 格式化为目标数组字符串 return `[${filteredParts.join(', ')}]`; } // 测试输入的句子列表 const targetSentences = [ 'The <a href="sy.com" id="sy">sky</a> is clear and the <a href="st.com" class="st">stars</a> are twinkling.', 'They were <a href="etc.com" id="et">excited</a> to see their first sloth.', 'Douglas figured the best way to <a href="etc.com" id="et">succeed</a> was to do the <a href="opt.com" class="op">opposite</a> of what he\'d been doing all his life.' ]; // 输出结果 targetSentences.forEach(sentence => console.log(splitSentence(sentence)));
最终输出
运行代码后会得到你期望的格式:
[The, <a href="sy.com" id="sy">sky</a>, is clear and the, <a href="st.com" class="st">stars</a>, are twinkling.] [They were, <a href="etc.com" id="et">excited</a>, to see their first sloth.] [Douglas figured the best way to, <a href="etc.com" id="et">succeed</a>, was to do the, <a href="opt.com" class="op">opposite</a>, of what he'd been doing all his life.]
内容的提问来源于stack exchange,提问作者Joven Dev
相关产品推荐
相关产品推荐

