gpt4 book ai didi

正则表达式匹配不在括号、赞誉或方括号中的空格

转载 作者:行者123 更新时间:2023-12-04 23:02:53 25 4
gpt4 key购买 nike

我试图用空格/空格分割一个句子,但我必须排除括号内的空格 () , 荣誉 {}或方括号 [] .

前字符串:[apples carrots] (car plane train) {food water} foo bar应该产生一个包含以下内容的数组:

  • 【苹果胡萝卜】
  • (汽车飞机火车)
  • {食水}
  • foo
  • 酒吧

  • 有任何想法吗?

    最佳答案

    不是 split ,而是匹配和修剪。示例是在 JavaScript 中,您可以在浏览器控制台中尝试:

    var a = '[apples carrots] (car plane train) {food water} foo bar';
    a.match(/[a-zA-Z0-9\[\]\(\){}]+/g).map(function (s) { return s.replace(/[\[\]\(\)\{\}]/, ''); });
    ["apples", "carrots", "car", "plane", "train", "food", "water", "foo", "bar"]

    或者:
    a.split(/\s+(?![^\[]*\]|[^(]*\)|[^\{]*})/)

    产生:
    ["[apples carrots]", "(car plane train)", "{food water}", "foo", "bar"]

    关于正则表达式匹配不在括号、赞誉或方括号中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18861381/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com