簡體   English   中英

正則表達式將字符串拆分為非常大的塊

[英]Regex to split string into verying size chunks

我試圖將一個字符串分成大小不同的塊,從而產生一波“波”,例如:

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

由於單詞的長度各不相同,因此我想在最近的空格處拆分。

我可能只想用一條線做太多事情。 但是我不喜歡循環的想法。 我從這里開始:

/.{5}\w*/g

我試過在周圍加上(),再加上{},但不能完全理解正則表達式。 這可能嗎? 還是會涉及某種循環?

我認為即使使用正則表達式也可以完成某些操作,但很大程度上取決於輸入字符串。 另外,您將不得不考慮如何排列塊,是否修剪,如何填充等,​​因此僅使用正則表達式是不行的。

此正則表達式模式: ((?:[^\\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

參見演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM