将字符串拆分为多个分隔符,同时保留一个或多个分隔符

有没有一种方法可以根据多个分隔符拆分字符串,同时在拆分数组中保留一些分隔符?"This is a-weird string,right?"所以如果我有我想要的字符串

["This", "is", "a", "-", "weird", "string", ",", "right", "?"]

我尝试过使用string.split(/([^a-zA-Z])/g),但我不想保留空格。本指南似乎是我可以使用的东西,但我对正则表达式的理解还不够好,不知道如何混合这两者。


米脂
浏览 336回答 3
3回答

慕的地8271018

您可以使用console.log("This is a-weird string,right?".match(/[^\W_]+|[^\w\s]|_/g))正则表达式匹配:[^\W_]+- 一个或多个字母数字字符|- 或者[^\w\s]- 除单词和空格之外的任何字符|- 或者_- 下划线。请参阅正则表达式演示。一个完全支持 Unicode 的正则表达式将是console.log("This is ą-węird string,right?".match(/[\p{L}\p{M}\p{N}]+|[\p{P}\p{S}]/gu))这里,[\p{L}\p{M}\p{N}]+- 一个或多个 Unicode 字母、变音符号或数字|- 或者[\p{P}\p{S}]- 单个标点符号或符号字符。请参阅此正则表达式演示。

弑天下

这是正则表达式分割方法。我们可以尝试按照以下模式进行拆分:\s+|(?<=\w)(?=\W)|(?<=\W)(?=\w)代码片段:var input = "This is a-weird string,right?";var parts = input.split(/\s+|(?<=\w)(?=\W)|(?<=\W)(?=\w)/);console.log(parts);这是对所使用的正则表达式模式的解释,它表示要分割:\s+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; whitespace|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OR(?<=\w)(?=\W)&nbsp; the boundary between a word character preceding and non word&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;character following|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OR(?<=\W)(?=\w)&nbsp; the boundary between a non word character preceding and word&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;character following

蓝山帝景

尝试这样:const str = "This is a-weird string,right?";var arr = str.replace(/(\S)([\,\-])/g, "$1 $2").replace(/([\,\-])(\S)/g, "$1 $2").split(" ");console.log(arr);您可以使用您感兴趣的每个分隔符进行替换,以便它的每一侧都有一个空格,然后使用它来分割并返回一个数组。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript