using RegExp to split string but store whitespace (space or crlf) to items

筅森魡賤 提交于 2019-12-13 04:17:19

问题


sample input (orgtext = a[crlf]b[space]c[crlf] )

I like to store each word a,b, c to the words array with the original suffix crlf or space. Currently calling SPLIT drops the suffix as its separator, but I like to store separator as well. Can I adjust regexp to return also suffix and still split?

Words = new Array; 
var ar: Array = orgtext.split( /\s+/  );   

for (var i:int = 0; i<ar.length;i++ )
{
Words.push(  ar[i] +"suffix here" ); 
}

回答1:


Generally you would use keep calling exec with an expression that uses the global (g) so that the lastIndex will be set.

var input : String = "asd asd asd asd";
var output : Array = new Array();

var expr : RegExp = /[^\s]+(?:$|\s+)/g;
var result : Object = expr.exec(input);

while(result != null)
{
    input.push(result[0].toString());
    result = expr.exec(input);
}

Depending on the number of matches you can expect, it might be faster to use...

([^\s]+(?:$|\s+))+

... which will capture all possible matches in one exec(). The matches will be available in result[1] ... result[n]



来源:https://stackoverflow.com/questions/555939/using-regexp-to-split-string-but-store-whitespace-space-or-crlf-to-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!