我试图一次将一个字符串按三个(但可以是任意数字)字符分组。使用此代码:
"this gets three at a time".scan(/\w\w\w/)
我得到:
["thi","get","thr","tim"]
但我想要得到的是:
["thi","sge","tst","hre","eat","ati","me"]
\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}/)
如果长度不能被 3 整除,也可以获得最后的 1 或 2。
"this gets three at a time".tr(" \t\n\r", "").scan(/.{1,3}/)
你也可以试试这些:
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}/)