【问题标题】:JavaScript split string with .match(regex)JavaScript 用 .match(regex) 分割字符串
【发布时间】:2016-06-15 14:37:56
【问题描述】:

来自 Mozilla 开发者网络的功能 split()

split() 方法返回新数组。

找到后,从字符串和子字符串中删除分隔符 在数组中返回。如果未找到或省略分隔符,则 数组包含一个由整个字符串组成的元素。如果 分隔符是一个空字符串,str转换为一个数组 字符。

如果分隔符是一个包含捕获的正则表达式 括号,然后每次匹配分隔符,结果 (包括任何未定义的结果)的捕获括号是 拼接到输出数组中。但是,并非所有浏览器都支持此功能 能力。

举个例子:

var string1 = 'one, two, three, four';
var splitString1 = string1.split(', ');
console.log(splitString1); // Outputs ["one", "two", "three", "four"]

这是一个非常干净的方法。我用一个正则表达式和一个稍微不同的字符串尝试了同样的方法:

var string2 = 'one split two split three split four';
var splitString2 = string2.split(/\ split\ /);
console.log(splitString2); // Outputs ["one", "two", "three", "four"]

这与第一个示例一样有效。在以下示例中,我再次更改了字符串,使用了 3 个不同的分隔符:

var string3 = 'one split two splat three splot four';
var splitString3 = string3.split(/\ split\ |\ splat\ |\ splot\ /);
console.log(splitString3); // Outputs ["one", "two", "three", "four"]

但是,正则表达式现在变得相对混乱。我可以对不同的分隔符进行分组,但是结果将包括这些分隔符:

var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\ (split|splat|splot)\ /);
console.log(splitString4); // Outputs ["one", "split", "two", "splat", "three", "splot", "four"]

所以我尝试在离开组时从正则表达式中删除空格,但没有多大用处:

var string5 = 'one split two splat three splot four';
var splitString5 = string5.split(/(split|splat|splot)/);
console.log(splitString5);

虽然,当我删除正则表达式中的括号时,分隔符在拆分字符串中消失了:

var string6 = 'one split two splat three splot four';
var splitString6 = string6.split(/split|splat|splot/);
console.log(splitString6); // Outputs ["one ", " two ", " three ", " four"]

另一种方法是使用match() 过滤掉分隔符,但我不太了解反向前瞻的工作原理:

var string7 = 'one split two split three split four';
var splitString7 = string7.match(/((?!split).)*/g);
console.log(splitString7); // Outputs ["one ", "", "plit two ", "", "plit three ", "", "plit four", ""]

它与开头的整个单词不匹配。老实说,我什至不知道这里到底发生了什么。


如何在结果中不包含分隔符的情况下使用正则表达式正确拆分字符串?

【问题讨论】:

  • 或许string5.split(/\s?(split|splat|splot)\s?/)
  • 如您所见,您不需要(也不想要)该组。因此,要将空格作为分隔符,您可以在每个交替中输入它们 - / split | splat | splot /

标签: javascript regex split


【解决方案1】:

使用非捕获组作为拆分正则表达式。通过使用非捕获组,拆分匹配将不会包含在结果数组中。

var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\s+(?:split|splat|splot)\s+/);
console.log(splitString4);
// Output => ["one", "two", "three", "four"]

【讨论】:

  • 嗨@anubhava 我很想知道如何在断点像 1. ,2 的情况下才拆分后面的字符串。等出现在字符串之间,例如字符串 =“1。在 9 月 29 日之前直接通过 Steam 下载。2。享受您的新 Steam 游戏!” .
  • 对不起,我没有正确理解您的问题
【解决方案2】:

如果你想使用match你可以这样写

'one split two split three split four'.match(/(\b(?!split\b)[^ $]+\b)/g)
["one", "two", "three", "four"]

它有什么作用?

  • \b匹配单词边界

  • (?!split\b)负向向前看,检查单词是否不是 split

  • [^ $]+ 匹配除空格或 $ 以外的任何内容,字符串结尾。此模式将匹配一个单词,前瞻确保它匹配的不是split

  • \b 匹配词尾。

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多