【问题标题】:Getting n pairs from a sequence of strings [duplicate]从字符串序列中获取n对[重复]
【发布时间】:2019-07-31 08:25:24
【问题描述】:

是否有一种使用 javascript 的方法可以返回构成较大字符串一部分的 n 字符串序列?

例如,按如下顺序:

Paris, Italy, London, Perth, Moscow, Wellington

在这个例子中我怎么能得到n word-pairs where n = 2。输出将是:

Paris, Italy
London, Perth
Moscow, Wellington

是否有内置的 Javascript 方法可以帮助我实现这一目标?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用匹配非空格字符的正则表达式,后跟逗号和空格,然后是更多非空格字符(匹配后的下一个字符是逗号或字符串结尾):

    const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
    console.log(
      input.match(/\S+, \S+(?=,|$)/g)
    );

    对于额外的单词序列,重复最初的非空格字符,后跟逗号和空格,例如:

    const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
    console.log(
      input.match(/(?:\S+, ){2}\S+(?=,|$)/g)
    );

    以上匹配 3 个单词。对于 4 个字,只需将 {2} 更改为 {3},依此类推。

    如果你想要一个函数,把你需要的字数传入new RegExp

    const getPairs = (str, words) => {
      const pattern = new RegExp(String.raw`(?:\S+, ){${words - 1}}\S+(?=,|$)`, 'g');
      return str.match(pattern);
    };
    
    const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
    console.log(
      getPairs(input, 3)
    );

    【讨论】:

    • 如果我需要 3 对单词怎么办?比如Paris, Italy, London为一等?
    • 只需根据需要多次重复模式的初始(非空格后跟空格)部分
    • 好的。还有一种方法可以制作动态正则表达式。例如,可以在旅途中使用数字,例如 23?
    • new RegExp 创建模式,代入要重复的单词数(减一)
    【解决方案2】:

    您可以通过使用模数对它们进行分组来做到这一点,从而获得相关的块大小:

    const input = 'Paris, Italy, London, Perth, Moscow, Wellington';
    
    const groupBy = f => arr => arr.reduce((prev, curr, i) => {
      const key = f(curr, i);
      const hasKey = prev.hasOwnProperty(`${key}`);
      
      return {
        ...prev,
        [key]: [...(hasKey ? prev[key] : []), curr]
      }
    }, {})
    
    const grouper = size => (_, i) => i % size;
    
    const splitIntoChunks = (chunkSize, arr) => Object.values(groupBy(grouper(arr.length / chunkSize))(arr))
    
    console.dir(splitIntoChunks(2, input.split(', ')))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多