【问题标题】:Typescript string.split with regex with char followed by space and space onlyTypescript string.split with regex with char 后跟空格和空格
【发布时间】:2019-10-02 14:11:51
【问题描述】:

我有一个这种类型的字符串:

string = "test1; test2, test3 test4;test5"

我需要拆分它并得到一个包含 5 个单词的数组。我这样做:

let arrayTo:string[] = string.split(/;|,|, |; | /);

但我得到的是一个由 7 个元素组成的数组,其中两个是空字符串:

["test1","","test2","","test3","test4","test5"]

我想考虑 , 和 ;后跟空白作为一个实体并在它们上拆分,但使用此正则表达式,它也会在这些字符后面的空白上拆分。但我还需要单独按空格进行拆分(在这种情况下,它正确地将 test3test4 拆分为两个实体)。
这样做的正确方法是什么?

【问题讨论】:

  • 你先用;(半列)分割,而不是; (半列空间)。
  • 试试split(/[;,]\s*|\s+/)

标签: regex string typescript split


【解决方案1】:

你可以使用

string.split(/[;,]\s*|\s+/)

正则表达式匹配

  • [;,]\s* - ;, 然后是 0+ 个空格
  • | - 或
  • \s+ - 1+ 个空格。

JS 演示:

string = "test1; test2, test3 test4;test5";
console.log(string.split(/[;,]\s*|\s+/));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2016-01-09
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多