gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:57:54 24 4
gpt4 key购买 nike

来自 Mozilla 开发者网络的函数 split():

The split() method returns the new array.

When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.

举个例子:

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", ""]

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


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

最佳答案

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

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"]

关于JavaScript 使用 .match(regex) 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37838532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com