创建包含字符串单个字符的数组.这些正则表达式是如何工作的

Create array containing the single chars of a string. How does these regular expression work?

本文关键字:何工作 工作 正则表达式 字符串 包含 单个 字符 数组 创建      更新时间:2023-09-26

我想我从一些示例代码开始:

var sentence = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
// Makes an array with the single chars of the sentence as elements.
sentence = sentence.split(''); 
// Makes a multi-dimensional array. 
var result = sentence.map(function(ch) {
  // Using /./ leads to an multi-dimensional array too.
  //  Each array contains two empty strings as elements.
  //  => ["", ""]
  return ch.split(/. /); 
});
result.forEach(function(item, i) {
  console.log(item);  // [ ["L"], ["o"], ["r"] ... ] 
});

目的对我来说很清楚:这是为了创建一个多维数组。每个元素得到句子的一个字符。

我不明白的是使用的正则表达式。

。表示正则表达式中的任意一个字符。

点(.)后面空白的目的是什么??

此外:如果我去掉空格,只写/。/那么结果也是数组。每个数组包含两个空字符串(")。

我也不清楚那种行为。

有人能解释描述的正则表达式行为吗?

喜欢添加:我在这里看到了代码片段…https://davidwalsh.name/write-javascript-promises

在"Chaining"部分的底部

"x".split(/. /)

的效果相同
"x".split(/rabbit/)

它只收集字符串中不包含分隔符的部分(=整个字符串),然后停止。

"x".split(/./)

收集不匹配.的部分(=空字符串),然后使用分隔符(= x),然后将字符串的其余部分(为空)附加到结果中。