gpt4 book ai didi

javascript - 寻找一个正则表达式将字符串分成 2,3,4... 个单词

转载 作者:行者123 更新时间:2023-11-28 19:21:08 25 4
gpt4 key购买 nike

假设我有这个字符串:

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

感觉不太对劲,看起来不太优雅。有些词也“悬而未决”。

最佳答案

使用\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' ]

关于javascript - 寻找一个正则表达式将字符串分成 2,3,4... 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28896885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com