【问题标题】:How to split a string in two by first digit occurrence?如何通过第一个数字出现将字符串分成两部分?
【发布时间】:2021-06-08 13:14:52
【问题描述】:

有这样的字符串

str = "word 12 otherword(s) 2000 19"

或者像这样

str = "word word 12 otherword(s) 2000 19"

我需要将字符串一分为二,才能得到这样的数组:

newstr[0] = first part of the string(即第一种情况下的“word”,第二种情况下的“word word”);

newstr[1] = rest of the string(即“12 otherword(s) 2000 19”在这两种情况下)。

我尝试使用splitregex 完成此操作,但没有成功:

str.split(/\d.*/) 返回Array [ "word ", "" ]Array [ "word word ", "" ]

str.split(/^\D*/gm) 返回Array [ "", "12 otherword(s) 2000 19" ]

你能给我一个建议吗?即使不使用 splitregex - 如果有更好/更快(Vanilla JavaScript)的解决方案。

【问题讨论】:

    标签: javascript regex split substring


    【解决方案1】:

    这里发生了 3 件事。

    1. String.split 通常在返回数组中不包含匹配的分隔符。所以拆分abc.split('b') 将返回['a', 'c']。可以通过使用匹配的正则表达式组来更改此行为;即添加括号'abc'.split(/(b)/) 将返回['a', 'b', 'c']

    2. String.split 将分隔符与其他元素分开。 IE。 'abc'.split(/(b)/) 将返回 3 个元素 ['a', 'b', 'c']。在正则表达式后缀.* 以组合最后两个元素:'abc'.split(/(b.*)/) 将返回['a', 'bc', '']

    3. 最后,为了忽略最后一个空元素,我们发送2 的第二个参数。

    let str = "word word 12 otherword(s) 2000 19";
    let splitStr = str.split(/(\d.*)/, 2);
    console.log(splitStr);

    【讨论】:

      【解决方案2】:

      你可以匹配这些部分:

      const strs = ["word 12 otherword(s) 2000 19", "word word 12 otherword(s) 2000 19"];
      for (var s of strs) {
        const [_, part1, part2] = s.match(/^(\D*)(\d+[\w\W]*)/)
        console.log([part1, part2])
      }

      请参阅regex demo

      正则表达式详细信息

      • ^ - 字符串的开头
      • (\D*) - 第 1 组:除数字以外的任何零个或多个字符
      • (\d+[\w\W]*) - 第 2 组:一位或多位数字,然后是尽可能多的零个或多个字符。

      请注意,您可以在使用时.trim() 生成的部件(使用console.log([part1.trim(), part2.trim()]) 打印它们)。

      【讨论】:

        猜你喜欢
        • 2015-10-09
        • 1970-01-01
        • 1970-01-01
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多