Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用正则表达式按空格拆分字符串_Node.js_Regex_Coffeescript - Fatal编程技术网

Node.js 使用正则表达式按空格拆分字符串

Node.js 使用正则表达式按空格拆分字符串,node.js,regex,coffeescript,Node.js,Regex,Coffeescript,假设我有一个字符串str=“abcde”str.split(“”)给了我一个元素数组[a,b,c,d,e]。 如何使用正则表达式获得此匹配 例如: str.match(/some regex/)给出['a','b','c','d','e']根据您的用例,您可以尝试const regex=/(\w+)/g 这会一次或多次捕获任何单词(与[a-zA-Z0-9_])字符。这假设您可以在空格分隔的字符串中包含长度超过一个字符的项 下面是我在regex101中制作的一个示例: const regex =

假设我有一个字符串
str=“abcde”
str.split(“”)
给了我一个元素数组[a,b,c,d,e]。 如何使用正则表达式获得此匹配

例如:
str.match(/some regex/)给出['a','b','c','d','e']

根据您的用例,您可以尝试
const regex=/(\w+)/g

这会一次或多次捕获任何单词(与[a-zA-Z0-9_])字符。这假设您可以在空格分隔的字符串中包含长度超过一个字符的项

下面是我在regex101中制作的一个示例:

const regex = /(\w+)/g;
const str = `a b c d efg  17 q q q`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
String.split()支持将regex作为参数

let str = 'a b c d e';
str.split(/ /);
// [ 'a', 'b', 'c', 'd', 'e' ]

let str = 'a01b02c03d04e';
str.split(/\d+/);
// [ 'a', 'b', 'c', 'd', 'e' ]