将每个索引的字符串拆分为n个单词的数组 [英] split string into array of n words per index
问题描述
我有一个要分割成一个数组的字符串,该数组每个索引有(例如)3个单词. 我还想做的是,如果在该字符串中遇到换行符,它将跳过" 3个单词的限制,并将其放入新索引中,并开始在该新索引中添加单词,直到再次达到3 .例子
I have a string that I'd like to split in an array that has (for example) 3 words per index. What I'd also like it to do is if it encounters a new line character in that string that it will "skip" the 3 words limit and put that in a new index and start adding words in that new index until it reaches 3 again. example
var text = "this is some text that I'm typing here \n yes I really am"
var array = text.split(magic)
array == ["this is some", "text that I'm", "typing here", "yes I really", "am"]
我已经尝试研究正则表达式,但是到目前为止,我还不能真正理解正则表达式中使用的语法.
I've tried looking into regular expressions, but so far I can't really make sense of the syntax that is used in regex.
我已经编写了一种复杂函数的方法,该方法将字符串分成3行,方法是先使用.split(" ");
将其分成单独的单词数组,然后使用循环将每3个字符串添加到另一个数组中.但是我不能考虑换行符.
I have written a way to complicated function that splits my string into lines of 3 by first splitting it into an array of separate words using .split(" ");
and then using a loop to add add it per 3 into another array. But with that I can't take the new line character into account.
推荐答案
您可以尝试以下模式:
var result = text.match(/\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g);
由于量词{0,2}
在默认情况下是贪婪的,因此只有找到换行符后,它的值才会小于2 (N-1)(因为此处不允许换行符) :[^\w\n]+
)或如果您是字符串的结尾.
since the quantifier {0,2}
is greedy by default, it will take a value less than 2 (N-1) only if a newline is found (since newlines are not allowed here: [^\w\n]+
) or if you are a the end of the string.
这篇关于将每个索引的字符串拆分为n个单词的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!