上代码
const strings = [
"[TextContent(type='text', text='地区:Beijing, CN\\n温度: 34.2°C\\n湿度: 31%\\n风速: 5.57 m/s\\n天气: 晴\\n', annotations=None)]",
"[TextContent(type='text', text='Created workbook at /home/user/meetings_weekly.xlsx', annotations=None)]",
"[TextContent(type='text', text='{\"code\":200,\"message\":\"操作成功\",\"data\":[]}', annotations=None)]",
"[TextContent(type='text', text='{\\\"code\\\":200,\\\"message\\\":\\\"操作成功\\\",\\\"data\\\":[]}', annotations=None)]",
"[TextContent(type='text', text='\\\"\\\"', annotations=None)]"
];
// 提取函数
function extractTextContent(str) {
// 使用正则表达式匹配 text='...' 到 annotations 之前的内容
const regex = /text=('.*?')(?=,\s*annotations)/s;
const match = str.match(regex);
if (match && match[1]) {
// 返回匹配到的内容(包括单引号)
return match[1];
}
return null;
}
// 提取所有字符串中的 text 内容
strings.forEach((str, index) => {
const extracted = extractTextContent(str);
console.log(`字符串 ${index + 1}:`, extracted);
});
输出结果
text
字符串 1: '地区:Beijing, CN\n温度: 34.2°C\n湿度: 31%\n风速: 5.57 m/s\n天气: 晴\n'
字符串 2: 'Created workbook at /home/user/meetings_weekly.xlsx'
字符串 3: '{"code":200,"message":"操作成功","data":[]}'
字符串 4: '{\"code\":200,\"message\":\"操作成功\",\"data\":[]}'
字符串 5: '\"\"'
代码说明
正则表达式 text=('.?')(?=,\sannotations):
text= 匹配固定开头
(‘.*?’) 非贪婪匹配单引号内的任何内容
(?=,\s*annotations) 正向预查,确保后面是逗号和 annotations
特殊字符处理:
正则表达式中的 s 标志使 . 能匹配换行符
可以正确处理包含转义字符的内容
返回值:
返回的是 text=‘…’ 中的 ‘…’ 部分(包括单引号)
如果需要去掉单引号,可以修改为 return match[1].slice(1, -1)
增强版本(去掉单引号)
javascript
function extractTextContent(str) {
const regex = /text='(.*?)'(?=,\s*annotations)/s;
const match = str.match(regex);
return match ? match[1] : null;
}
在 Markdown 中要将 \n 转换为实际换行(回车)
const text = "地区:Beijing, CN\\n温度: 34.2°C\\n湿度: 31%";
const markdownText = text.replace(/\\n/g, ' \n'); // 转换为Markdown换行
console.log(markdownText);
// 输出:地区:Beijing, CN
// 温度: 34.2°C
// 湿度: 31%
在vue中的使用

效果展示:



3994

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



