2 回答
TA贡献1818条经验 获得超8个赞
如果涉及到可靠性、便利性和/或可维护性,人们应该考虑一种更通用的方法,它确实减少了行/字符串列表,此外还通过组装正确的正则表达式来考虑特定主题......
const fileData = `
Topic:Cat [0] at offset:216712{"ID":55689534,"NAME":6}
Topic:Cat [1] at offset:216719{"ID":55689524,"NAME":6}
Topic : Bat [0] at offset:216716 {"CODE":94762151097,"AGE":32}
Topic:Cat [0] at offset:216713{"ID":55689524,"NAME":6}
Topic:Bat [1] at offset:216723{"CODE":947080272531,"AGE":43}
Topic:Cat [1] at offset:216738{"ID":55689525,"NAME":6}
`;
const dataItemList = fileData.split(/\n/);
function getTopicSpecificDataCaptureRegX(topic) {
// see also: [https://regex101.com/r/AD31R6/1/]
//return (/^\s*Topic\s*\:\s*Bat[^{]+(\{.*\})\s*$/);
//return (/^\s*Topic\s*\:\s*Cat[^{]+(\{.*\})\s*$/);
return RegExp('^\\s*Topic\\s*\\:\\s*' + topic + '[^{]+(\\{.*\\})\\s*$');
}
function collectTopicSpecificData(collector, dataItem) {
const result = dataItem.match(collector.regX);
if (result !== null) {
collector.list.push(JSON.parse(result[1]));
}
return collector;
}
console.log(
'"Cat" specific data list : ',
dataItemList.reduce(collectTopicSpecificData, {
regX: getTopicSpecificDataCaptureRegX('Cat'),
list: []
}).list
);
console.log(
'"Bat" specific data list : ',
dataItemList.reduce(collectTopicSpecificData, {
regX: getTopicSpecificDataCaptureRegX('Bat'),
list: []
}).list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
TA贡献1777条经验 获得超10个赞
让 new = line.match(paramsPattern);
您不应该将其分配给变量 new ... new 是特殊的。
这是适用于您的示例的正则表达式:https ://regex101.com/r/tBHRIY/1
这是一个例子:
const testLine = 'Topic:Bat [0] at offset:216812{"ID":51255125, "NAME":6}';
function transform(line) {
const paramsPattern = /({[\s\S]+})/g;
const match = line.match( paramsPattern );
if ( line.indexOf( 'Bat' ) === -1 )
return null;
if ( match === null )
return null;
// This will verify that the json is valid ( it will throw ) but you can skip this and return match[0] directly if you are sure it is valid
return JSON.stringify( JSON.parse( match[0] ) );
}
console.log( transform( testLine ) );
编辑:抱歉,我错过了检查 BAT,已添加
添加回答
举报