2013-06-13 38 views
0

我試圖用一次三個字符串(但可以是任意數字)對字符串進行分組。使用此代碼:一次獲取字符組nn

"this gets three at a time".scan(/\w\w\w/) 

我得到:

["thi","get","thr","tim"] 

但是我想要得到的是:

["thi","sge","tst","hre","eat","ati","me"] 
+1

可以請你代替與<空字符串>? – NeverHopeless

回答

3

\w匹配的字母數字和下劃線(即它是[a-zA-Z0-9_]速記),而不是空格。儘管如此,它並沒有奇蹟般地跳過空格,正如你所期望的那樣。

所以,你首先必須把空格去掉:

"this gets three at a time".gsub(/\s+/, "").scan(/.../) 

或非單詞字符:

"this gets three at a time".gsub(/\W+/, "").scan(/.../) 

你的三個字符匹配之前。

雖然你應該寧願使用

"this gets three at a time".gsub(/\W+/, "").scan(/.{1,3}/) 

也獲得最後1或2,如果長度不被3整除

+0

再次感謝您的詳細解釋和答案:-) – user1297102

1
"this gets three at a time".tr(" \t\n\r", "").scan(/.{1,3}/) 
+1

你的解決方案也是一個很好的解決方案,基本上與被接受的答案一樣,但是我認爲我應該選擇一個有恭維的解釋。我會在將來繼續使用'tr',謝謝。 – user1297102

1

您可以嘗試以下以及:

sentence = "this gets three at a time" 
sentence[" "] = "" 
sentence.scan(/\w\w\w/) // no change in regex 

或者:

sentence = "this gets three at a time" 
sentence[" "] = "" 
sentence.scan(/.{1,3}/) 

或者:

sentence = "this gets three at a time" 
sentence[" "] = "" 
sentence.scan(/[a-zA-Z]{1,3}/) 
+0

感謝您的回覆,在另一篇文章中解釋說我需要先刪除空格。我想每個人都知道除我以外的{1,3}語法! – user1297102

+1

是的,我告訴過你。由於我發現你的正則表達式完整,但錯過了刪除空間。 – NeverHopeless

+0

你是正確的,複製。謝謝! :) – user1297102

相關問題