40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import XRegExp from 'xregexp'
|
|
|
|
// Parse the log data
|
|
const parseLog = (data: string) => {
|
|
const patterns = [
|
|
XRegExp('^NAME:\\s+"(?<name>.*)",\\s+DESCR:\\s+"(?<descr>.*)"'),
|
|
XRegExp('^PID:\\s+(?<pid>[\\S+]+|.*),.*VID:\\s+(?<vid>.*),.*SN:\\s+(?<sn>[\\w+\\d+]*)'),
|
|
XRegExp('^PID:\\s+,.*VID:\\s+(?<vid>.*),.*SN:\\s+(?<sn>[\\w+\\d+]*)'),
|
|
XRegExp('^PID:\\s+(?<pid>[\\S+]+|.*),.*VID:\\s+(?<vid>.*),.*SN:'),
|
|
]
|
|
const lines = data.split('\n')
|
|
const records = []
|
|
let currentRecord: any = { name: '', descr: '', pid: '', vid: '', sn: '' }
|
|
|
|
for (const line of lines) {
|
|
for (const pattern of patterns) {
|
|
const match = XRegExp.exec(line, pattern)
|
|
if (match) {
|
|
const item = match?.groups
|
|
// Update current record with matched fields
|
|
Object.keys(currentRecord).forEach((key) => {
|
|
if (item && item[key] !== undefined) {
|
|
currentRecord[key] = item[key]
|
|
}
|
|
})
|
|
// If "pid", "vid", or "sn" are matched, push a completed record
|
|
if (currentRecord.pid || currentRecord.vid || currentRecord.sn) {
|
|
records.push({ ...currentRecord })
|
|
currentRecord = { name: '', descr: '', pid: '', vid: '', sn: '' } // Reset for the next record
|
|
}
|
|
break // Stop checking other patterns for this line
|
|
}
|
|
}
|
|
}
|
|
|
|
return records
|
|
}
|
|
|
|
export default parseLog
|