开发者

Regex Split after 20 characters

I have a fixed width text file where each field is given 20 characters total. Usually only 5 characters are used and then there is trailing whitespace. I'd like 开发者_如何学Cto use the Split function to extract the data, rather than the Match function. Can someone help me with a regex for this? Thanks in advance.


I would do this with string manipulation, rather than regex. If you're using JavaScript:

var results = [];

for (i = 0; i < input.length; i += 20) {
    results.push(input.substring(i, i + 20));
}

Or to trim the whitespace:

var results = [];

for (i = 0; i < input.length; i += 20) {
    results.push(input.substring(i, i + 20).replace(/^\s+|\s+$/g, ''));
}

If you must use regex, it should just be something like .{20}.


Split on whitespaces and get the first returned element. This is under the assumption that you do not have whitespaces within the actual data.

cheers


If you must:

^(.{20})(.{20})(.{20})$ // repeat the part in parentheses for each field

You still need to trim each field to remove trailing whitespace.

It seems simpler to use substr() or your languages equivalent. Or in PHP you could use str_split($string, 20).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜