Aks*_*pte 0 regex node.js coffeescript
假设我有一个字符串str = "a b c d e".str.split(' ')给我一系列元素[a,b,c,d,e].我如何使用正则表达式来获得这个匹配?
例如:str.match(/ some regex /)给出['a','b','c','d','e']
小智 6
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' ]
Run Code Online (Sandbox Code Playgroud)
根据您的用例,您可以尝试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}`);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
652 次 |
| 最近记录: |