使用正则表达式按空格拆分字符串
Split a string by spaces using regex
假设我有一个字符串 str = "a b c d e"
。 str.split(' ')
给我一个元素数组 [a,b,c,d,e]。
我如何使用正则表达式来获得这个匹配项?
例如:
str.match(/some regex/) 给出 ['a','b','c','d','e']
根据您的使用情况,您可以尝试 const regex = /(\w+)/g;
这会捕获任何单词(与 [a-zA-Z0-9_] 相同)字符一次或多次。这假设您的 space 分隔字符串中可以包含长度超过一个字符的项目。
这是我在 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() 支持正则表达式作为参数;
String.prototype.split([separator[, limit]])
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' ]
假设我有一个字符串 str = "a b c d e"
。 str.split(' ')
给我一个元素数组 [a,b,c,d,e]。
我如何使用正则表达式来获得这个匹配项?
例如: str.match(/some regex/) 给出 ['a','b','c','d','e']
根据您的使用情况,您可以尝试 const regex = /(\w+)/g;
这会捕获任何单词(与 [a-zA-Z0-9_] 相同)字符一次或多次。这假设您的 space 分隔字符串中可以包含长度超过一个字符的项目。
这是我在 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() 支持正则表达式作为参数;
String.prototype.split([separator[, limit]])
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' ]