JavaScript使用.match(regex)分割字符串

19

在 Mozilla 开发者网络中,函数 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?/). - SeinopSys
正如你所发现的那样,你不需要(也不想要)这个组。因此,为了将空格包含在分隔符中,你可以在每个交替中输入它们 - / split | splat | splot / - SamWhan
2个回答

28
使用非捕获组作为分割正则表达式。通过使用非捕获组,分割匹配将不会包含在结果数组中。
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游戏!” - HaryanviDeveloper
抱歉,我没有完全理解您的问题。 - anubhava

3
如果您想使用match,可以这样写:
'one split two split three split four'.match(/(\b(?!split\b)[^ $]+\b)/g)
["one", "two", "three", "four"]

它是什么?

  • \b 匹配单词边界

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

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

  • \b 匹配单词结尾。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接