Reputation: 143
I have a text file that needs to be parsed correctly. The text file looks like this:
[header]
[header 2]
[ header3 ]
I can grab these headers by doing so
var expression:RegExp = /[ [a-z0-9 ]+ ]/igxm;
var items:Array = text.match(expression);
But I would also like to remove the white space from before and after the brackets, so the headers can align against the left edge. Also, for [ header3 ], I would like to remove the white space inside the brackets, before "h" and after "3". What would be the correct regex for something this? Thanks in advance.
tone
Upvotes: 0
Views: 466
Reputation: 4434
and a lil bit other way:
var str:String = "[header]\n [header 2]\n [ header3 ] ";
var tmpArr:Array = str.match(/\[\s*\w+\s*\d*\s*\]/gm);
for (var i:int = 0; i < tmpArr.length; i++ ) {
tmpArr[i] = tmpArr[i].replace(/(\[)\s+(\S.+\S)\s+(\])/g, '$1$2$3');
}
trace(tmpArr.join('\n'));
/*-outputs-
[header]
[header 2]
[header3]
---------*/
Upvotes: 1
Reputation: 3273
Something like:
var expression:RegExp = /\[[ ]*([a-z0-9 ]*[a-z0-9]+)[ ]*\]/igxm;
var header:String = text.replace(expression, "$1");
This assumes you only have one match per-line (you run the same regexp over each line). If you want to run through the whole string, you can run the same regex with String.match() and then use the snippet above to extract the group.
Upvotes: 1