如何优雅地解析Java字符串中的数字和范围?

I would like to convert a string like "1 2 3-5" to an array of numbers [1, 2, 3, 4, 5].

Following the robustness principle, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is A-B to represent range from A to B (inclusive). Also, it's ok to ignore malformed input (like 1-3-5), it can be considered "undefined behavior" as long as it doesn't raise an exception.

我当前的代码如下:

function parse(string) {
    let numbers = [];
    for (let match of string.match(/[0-9]+(?:\-[0-9]+)?/g)) {
        if (match.includes("-")) {
            let [begin, end] = match.split("-");
            for (let num = parseInt(begin); num <= parseInt(end); num++) {
                numbers.push(num);
            }
        } else {
            numbers.push(parseInt(match));
        }
    }
    return numbers;
}

对于这样一个简单的任务,这似乎有些令人费解。使用“现代” JavaScript(我针对ES6)是否还有其他更简单的选择?

评论
  • ueaque
    ueaque 回复

    You can make it a bit nicer by using matchAll instead of match, allowing you extract the capture groups (the digits) immediately, rather than having to use an .includes check and split afterwards:

    function parse(string) {
        const numbers = [];
        for (const [, begin, end] of string.matchAll(/(\d+)(?:-(\d+))?/g)) {
            numbers.push(Number(begin));
            if (end) {
                for (let num = Number(begin) + 1; num <= Number(end); num++) {
                  numbers.push(num);
              }
            }
        }
        return numbers;
    }
    
    console.log(parse('11 14-16 18-20'));