【问题标题】:Regex to split string into verying size chunks正则表达式将字符串拆分为不同大小的块
【发布时间】:2015-03-17 22:28:50
【问题描述】:

我试图将一个字符串分成不同大小的块,创建一个“波浪”的单词,例如:

          the
        cat sat
     on the mat the
  cat sat on the mat the
     cat sat on the
        mat the
          cat

由于单词的长度不同,我想在最近的空间上进行拆分。

我可能试图用一条线做太多事情。但是我不喜欢循环的想法。我从这个开始:

/.{5}\w*/g

我尝试添加 () 并添加 {},但无法完全掌握正则表达式的窍门。这可能吗?还是会涉及某种循环?

【问题讨论】:

  • 循环有什么问题?
  • 正如 CoderDennis 所暗示的那样,RegEx 不是问题的答案。
  • 需要更精确地指定问题。您知道每行要显示多少个字符和/或单词吗?
  • 伙计们,正则表达式是 Javascript 的一个非常强大的部分,我已经被吓跑了很长时间(听起来你们中的一些人也有?)@phari,请参阅下面的答案,strubizhev 似乎完全理解。

标签: javascript regex


【解决方案1】:

我认为即使使用正则表达式也可以完成一些事情,但很大程度上取决于输入字符串。此外,您还必须考虑如何排列块、是否修剪、如何填充等,​​因此仅使用正则表达式是行不通的。

这个正则表达式模式: ((?:[^\s]+(?:\s|$)){1,20}) 可以产生类似于您在以下字符串中查找的内容: the cat sat on the mat the cat sat on the mat the cat sat on the mat。它之所以起作用,是因为在应该发生故障的地方有额外的空间。

the 
cat sat 
on the mat the 
cat sat on the mat the 
cat sat on the 
mat

demo

【讨论】:

    猜你喜欢
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多