我正在尝试将字符串分组为三个(但可以是任意数字)字符。使用此代码:
"this gets three at a time".scan(/\w\w\w/)
我明白了:
["thi","get","thr","tim"]
但我想要的是:
["thi","sge","tst","hre","eat","ati","me"]
答案 0 :(得分: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整除。
答案 1 :(得分:1)
"this gets three at a time".tr(" \t\n\r", "").scan(/.{1,3}/)
答案 2 :(得分: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}/)