编辑代码

interface Word {
    /** 索引 指定位置 */
    index: number;
    /** 关键字 */
    keyword: string;
    /** 值 */
    value?: number;
}


const input = '温度19PH78规格是克,氨氮值0.5 99';
// console.log(parseDecimalNumbers(input))

// const keywords = ['PH', '温度', '规格', '氨氮']
const keywords = ['PH']

let txt = parseKeywords(input, keywords)
console.log('txt', txt)


function parseDecimalNumbers(input: string): number[] {
    const regex = /-?\b\d+(\.\d+)?\b/g; // 匹配整数或小数,包括负数
    const matches = input.match(regex);
    return matches ? matches.map(Number) : [];
}


function parseKeywords(input: string, keywords: string[]) {

    const wordSort: Word[] = [];
    // 获取关键字序号
    for (let i = 0; i < keywords.length; i++) {
        const keyword = keywords[i]
        const index = input.indexOf(keyword)
        if (index != -1) {
            wordSort.push({ index, keyword })
        }
    }

    // 升序排序
    wordSort.sort((a, b) => a.index - b.index);
    console.log(wordSort);

    for (let i = 0; i < wordSort.length; i++) {
        let word = wordSort[i];
        let end = i < wordSort.length - 1 ? wordSort[i + 1].index : undefined;
        // console.info('end', end)
        let start = word.index + word.keyword.length;
        let txt = input.substring(start, end)
        console.log(txt)
        // 解析数字
        let values = parseDecimalNumbers(txt);
        // console.log(values)
        if (values.length > 0) {
            // 写入第一个解析的数字
            word.value = values[0];
        }
    }

    return wordSort;
}