2 回答

TA貢獻(xiàn)1818條經(jīng)驗 獲得超8個贊
如果涉及到可靠性、便利性和/或可維護(hù)性,人們應(yīng)該考慮一種更通用的方法,它確實減少了行/字符串列表,此外還通過組裝正確的正則表達(dá)式來考慮特定主題......
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貢獻(xiàn)1777條經(jīng)驗 獲得超10個贊
讓 new = line.match(paramsPattern);
您不應(yīng)該將其分配給變量 new ... new 是特殊的。
這是適用于您的示例的正則表達(dá)式: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,已添加
添加回答
舉報