function parseQuestion(input) {
input = normalize(input);
const result = {stem:'',options:[]};
// 1️⃣ 题干
const lines = input.split('\n').map(l => l.trim()).filter(Boolean);
let isStemFinish = false;
for (const line of lines) {
// 跳过选项和答案
if(!isStemFinish){
if (isOptionLine(line)){
isStemFinish = true;
} else if(isAnswerLine(line)) {
isStemFinish = true;
} else {
const m = line.match(/^\s*(\d+)\s*[.、))]?\s*(.+)/);
if(m){
console.log(m[1]);
console.log(m[2].trim());
}
}
}
}
// 2️⃣ 选项
result.options = parseOptions(input);
// 3️⃣ 答案
result.answer = parseAnswer(input);
return result;
}
const text = `
1. 这是什么
是小动物
A 小鸟
B 小鸭
C 小猪
答案:A
`;
function isOptionLine(line) {
return /^\s*[A-D]\s*[\.、\)]?\s+/.test(line);
}
function isAnswerLine(line) {
return /^\s*答案\s*[::]/.test(line);
}
function normalize(text) {
return text
.replace(/<\/p>/gi, '\n') // 只处理</p>为换行
.replace(/<br\s*\/?>/gi, '\n') // 处理<br>标签
.replace(/<[^>]*>/g, '') // 移除所有HTML标签
.replace(/\r\n/g, '\n')
.replace(/[)]/g, ')')
.replace(/[.。]/g, '.')
.replace(/[:]]/g, ':')
.trim();
}
function parseOptions(text) {
const optionReg = /^\s*([A-Z])\s*[\.、\)]?\s*(.+)$/gm;
const options = {};
let match;
while ((match = optionReg.exec(text)) !== null) {
options[match[1]] = match[2].trim();
}
return Object.keys(options).length ? options : null;
}
function parseAnswer(text) {
const answerMatch = text.match(
// /答案:\s*([A-Z])/i
/答案\s*(?:[ .::]?\s*)?([A-Z]+)/i
);
if (!answerMatch) return null;
const raw = answerMatch[1].trim();
// 多选 or 单选
return raw
}
function parseStem(input) {
const lines = input.split('\n');
for (const line of lines) {
const m = line.match(/^\s*(\d+)\s*[\.、\)]?\s*(.*)$/);
if (m) {
return {
num: Number(m[1]),
stem: m[2].trim() // 可能为空,完全 OK
};
}
}
throw new Error('题干解析失败');
}
parseQuestion(text)
console