【问题标题】:Split string at every nth linebreak using javascript使用javascript在每第n个换行符处拆分字符串
【发布时间】:2017-09-30 03:23:47
【问题描述】:

我正在寻找一种解决方案,在每第 n 个换行符处拆分一个字符串。 假设我有一个有六行的字符串

"One\nTwo\nThree\nFour\nFive\nSix\n"

所以在第三个换行符处拆分会给我类似的东西

"One\nTwo\nThree\n" and "Four\nFive\nSix\n"

我已经找到了在第 n 个字符处执行此操作的解决方案,但我无法确定第 n 个字符长度会发生什么。 我希望我的问题很清楚。 谢谢。

【问题讨论】:

  • 不要尝试拆分,尽量匹配至少3行。
  • @CasimiretHippolyte 不太清楚该怎么做,我发现匹配多行的模式,很难找到匹配每 n 行的模式。
  • @HaiderAli 在这种情况下,当您的输入为One\n\n\n\n\nTwo\n\nThree\n\nFour\n\nFive\n\n\n\nSix\n 时,您希望输出如何?
  • @Gurman 这不会发生,字符串是从数组中以编程方式准备的。我宁愿拆分一个字符串而不是对一个数组进行分页;p

标签: javascript regex split


【解决方案1】:

使用String.prototype.match 方法而不是使用String.prototype.split 更容易:

"One\nTwo\nThree\nFour\nFive\nSix\n".match(/(?=[\s\S])(?:.*\n?){1,3}/g);

demo

图案细节:

(?=[\s\S]) # ensure there's at least one character (avoid a last empty match)

(?:.*\n?)  # a line (note that the newline is optional to allow the last line)

{1,3} # greedy quantifier between 1 and 3
      # (useful if the number of lines isn't a multiple of 3)

Array.prototype.reduce 的其他方式:

"One\nTwo\nThree\nFour\nFive\nSix\n".split(/^/m).reduce((a, c, i) => {
    i%3  ?  a[a.length - 1] += c  :  a.push(c);
    return a;
}, []);

【讨论】:

    【解决方案2】:

    直截了当:

    (?:.+\n?){3}
    

    a demo on regex101.com


    分解,这说:
    (?:  # open non-capturing group
    .+   # the whole line
    \n?  # a newline character, eventually but greedy
    ){3} # repeat the group three times
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多