说我有这个字符串:
This is a test sentence. Actually, it is a paragraph really. Lets see how this goes
我想在个别单词(包括标点符号)上进行分块。例如,一次2个单词:
This is
a test
sentence. Actually,
it is
a paragraph
really. Lets
see how
this goes
我可以使用以下方式获得单词:
/\w*(\D)\s*/g
太好了,但是当我用这样的东西尝试3个单词时:
/(\w*\D)\s(\w*\D)\s(\w*\D)/g
感觉不对,看起来并不优雅。有些话留下了"悬空"太
答案 0 :(得分:2)
使用\S+
匹配一个或多个非空格字符。
> var s = 'This is a test sentence. Actually, it is a paragraph really. Lets see how this goes'
undefined
> s.match(/\S+\s+\S+/g)
[ 'This is',
'a test',
'sentence. Actually,',
'it is',
'a paragraph',
'really. Lets',
'see how',
'this goes' ]
答案 1 :(得分:1)
你可以用它。而不是“3”,你想要的每行数字为1,如例子中所示(3给出4个单词)。
var s = 'This is a test sentence. Actually, it is a paragraph really. Lets see how this goes'
undefined
s.match(/(\S+)(\s+\S+){0,3}/g)
Array [ "This is a test", "sentence. Actually, it is", "a paragraph really. Lets", "see how this goes" ]