如何从多行字符串中提取信息?

时间:2016-11-05 17:56:25

标签: javascript regex

我有这个字符串:

1970/11/05 18:40:06
Transferred:      484844 Bytes (4745455 Bytes/s)
Errors:                46
Checks:              5550
Transferred:         5450
Elapsed time:        8.6s

我想从字符串中提取所有信息(数据除外)并保存为对象。正则表达式的问题是值的缩进,因为如果值变大,标签和值之间的空格会变小。 用Regex做任何事吗?

2 个答案:

答案 0 :(得分:2)

我认为你不应该使用正则表达式,而应该使用简单的Export-SPWeb http://dc/sites/Coms –Path "W:\Backups\cops.cmp" -IncludeVersions ALL -includeusersecurity split()。我将数据解析为Map,我发现这样的东西很好用,但你也可以使用一个对象......

map()

如果您更喜欢解决方案将其解析为对象:

var str =  `1970/11/05 18:40:06
Transferred:      484844 Bytes (4745455 Bytes/s)
Errors:                46
Checks:              5550
Transferred:         5450
Elapsed time:        8.6s`;

var splitted = str.split("\n");
splitted.shift();

var data = new Map(splitted.map(v => {
    var f = v.replace(/\s/gm, "").split(":");
    return [f[0], f[1]]
}));

console.log(data.get("Errors")); // 46

答案 1 :(得分:0)

绝对可以使用正则表达式,如果你真的需要使用正则表达式,那么你可以使用\ s +表达式,(一个或多个空白字符)。

相关问题