Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

请教一个分割特定字符串为数组的实现方法?

let data = '[foo bar]/[red]/1 [foo bar]/[blue]/2'

// => ['foo bar/red/1', 'foo bar/blue/2']

let data = '[foo bar]/[red]/1 [foo bar]/2'

// => ['foo bar/red/1', 'foo bar/2']

求一个更好的方法,谢谢各位大佬~~~~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

更新 2020-10-16

function splitIt(s) {
    return s
        // 直接 split 不行,但是可以先 replace 再 split
        // 原因不明,如果谁知道告诉一声,谢谢!!!
        .replace(/(?:(?<=(^|])[^[]*)s){1,}(?=.*?[)/g, "|")
        .split("|")
        .map(s => s.replace(/[[]]/g, ""));
}
console.log(splitIt(data));

测试用例:

const data = "23/23 23/25 23/[blue 1]/25 [1 foo bar]/[red]/1 23/[blue]/2 23/2 [blue]/2 [blue flow]/2";
console.log(splitIt(data));

// [
//     '23/23',
//     '23/25',
//     '23/blue 1/25',
//     '1 foo bar/red/1',
//     '23/blue/2',
//     '23/2',
//     'blue/2',
//     'blue flow/2'
// ]

这部分算是扯蛋,先括起来吧

匹配空白字符:/s+/g

然后,对其前导条件有要求:/(?<=.......)s+/g (省略号这里表示占位)

要求是不在括号内,也就是说,前面是反方括号,并且在这个反方括号和空白之间没有别的方括号或空白,
所以 /][^[s]*/,代入省略号:/(?<=][^[s]*)s+/g

还要考虑,一开始就没有方括号的情况,所以把 ] 变成 (^|],就是 /(?<=(?:^|])[^[s]*)s+/g


其实仔细思考一下,所有字符串都是用方括号包起来的,只要这个空格前面是数字,或者反方括号就符合条件,所以:/(?<=(?:d|]))s+/g

结果:

function splitIt(s) {
    return s
        .split(/(?<=(?:d|]))s+/g)
        .map(s => s.replace(/[[]]/g, ""));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...