gpt4 book ai didi

javascript - 在 JS 中拆分字符串

转载 作者:行者123 更新时间:2023-11-29 15:34:33 25 4
gpt4 key购买 nike

我需要拆分一个字符串,我需要从该字符串中获取三条信息,然后将其放入数组中,本质上,该数组将始终包含三个内容:[first, second, third],第二项和第三项可以为空。

该行将采用“First Second, Id”的形式。我需要忽略每个单词之后或每个单词之前的额外空格。

因此第一个和第二个单词之间用一个或多个空格区分,第二个单词和 Id 用逗号区分。

分割线的例子:

John Doe, 1234 => 结果:[John, Doe, 1234]

John [# spaces] Doe,[# spaces] 1234 => 结果:[John, Doe, 1234]

[# spaces] John [# spaces] Doe [# spaces] , [# spaces] 1234 => 结果:[John, Doe, 1234]

John , 1234 => 结果:[John,",",1234]

John => 结果:[John, "", ""]

我尝试使用正则表达式 line.split(/[\s,]+/),但它只适用于情况 1。

如何创建包含所有这些情况的正则表达式?

最佳答案

针对您提供的每个案例进行测试...

Note: As per you examples there must be a comma after the second capture groupto differentiate between two groups, or three.

All examples use .slice(1) to remove the first item from the returned array. This is because String.prototype.match returns an array including the original string.

示例一: one.match(regex)["John Doe, 1234", "John", "Doe", "1234"]

示例二: one.match(regex).slice(1)["John", "Doe", "1234"]

如果需要,您可以在数组中包含原始字符串,但为了尽可能准确地回答您的问题,我从索引 1 到数组末尾进行了切片。

var one = "John Doe, 1234";
var two = "John Doe, 1234";
var three = " John Doe , 1234 ";
var four = "John , 1234";
var five = "John";
var six = ""; // additional test.
var seven = "John doe"; // additional test.
var eight = "John Doe, " // additional test.

// Here is the regex...
var regex = /^\s*(\w*)\s*(\w*)\s*,?\s*(\w*)/;

one.match(regex).slice(1);
// result: ["John", "Doe", "1234"];

two.match(regex).slice(1);
// result: ["John", "Doe", "1234"];

three.match(regex).slice(1);
// result: ["John", "Doe", "1234"];

four.match(regex).slice(1);
// result: ["John", "", "1234"];

five.match(regex).slice(1);
// result: ["John", "", ""];

six.match(regex).slice(1);
// result: ["", "", ""];

seven.match(regex).slice(1);
// result: ["john", "doe", ""];

eight.match(regex).slice(1);
// result: ["John", "Doe", ""];

此外,在使用 new RegExp 构建正则表达式对象时,某些字符必须转义,这就是双“\”的原因。

关于javascript - 在 JS 中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896082/

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