JavaScript提取txt文件中包含DTCode或TxtID且带字母数字的数据
你可以使用以下代码来实现将txt文件中满足条件的数据提取出来并放到一个数组里:
const fs = require('fs');
// 读取txt文件内容
const fileContent = fs.readFileSync('file.txt', 'utf-8');
// 提取满足条件的数据
const dataArray = [];
const lines = fileContent.split('
');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes('DTCode') || line.includes('TxtID')) {
const regex = /[A-Za-z0-9]+/g;
const matches = line.match(regex);
if (matches) {
dataArray.push(...matches);
}
}
}
console.log(dataArray);
这段代码首先使用fs.readFileSync函数读取txt文件的内容,并使用split(' ')方法将内容按行分割成数组。然后使用for循环遍历每一行,判断是否包含‘DTCode’或‘TxtID’。如果包含,则使用正则表达式/[A-Za-z0-9]+/g匹配出所有的英文字母和数字,并使用match方法将匹配结果存入matches数组中。最后将matches数组中的元素使用push方法加入dataArray数组中。
最后,你可以通过console.log(dataArray)将结果打印出来。请记得将代码中的file.txt替换成你实际的txt文件路径。
原文地址: https://www.cveoy.top/t/topic/lkca 著作权归作者所有。请勿转载和采集!