我正在阅读一个文本文件并在我的 react 项目中使用正则表达式将其转换为 JSON 格式。它工作正常,但不包括文本文件的最后 20-30 行。将其转换为 JSON 时出现一些问题,但我无法理解该问题。
这是我的代码:
readTextFile = file => {
let rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = () => {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
let allText = rawFile.responseText;
// console.log(allText)
let reg = /\d\d\d\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])/g;
let arr = [];
let start = null;
let line, lastSpacePos;
let match;
while ((match = reg.exec(allText)) != null) {
if(start) {
line = allText.slice(start, match.index).trim();
lastSpacePos = line.lastIndexOf(' ');
arr.push({
date: line.slice(0, 19),
text: line.slice(20, lastSpacePos).trim(),
user_id: line.slice(lastSpacePos).trim()
});
}
start = match.index
}
console.log(arr);
this.setState({
// text: JSON.stringify(arr)
text: allText
});
}
}
};