gpt4 book ai didi

javascript - JS 正则表达式匹配引号内的逗号

转载 作者:太空宇宙 更新时间:2023-11-03 22:24:41 25 4
gpt4 key购买 nike

我正在尝试获取基于文本的日志文件,如下所示:

type: 'click', category: 'REFRESH_DOOR', desc: 'clicked refresh from door 0124', site: 'mysite', pathname: '/load_areas/all/doors', params: '?sort_by=code&layout=view_by_4', time: '1515838628166', mobile: 'false', bp: 'xlarge', size: '[1920, 935]', area: 'all', sid: '15158225889', facility: 'MMMM', IP Address: 'XXX.XXX.XXX.XXX', created: 'January 13, 2018 04:17'

并遍历它以从中构建 JSON 对象。当我在上面的条目上 log.split(",") 从字符串的各个部分中创建单独的对象时,它会获取日期并将其拆分,从而破坏数据。

什么是在单引号内查找逗号的正则表达式,我可以在尝试将此字符串拆分为 JS 数组之前替换它?

我基本上想将: 'January 13, 2018 04:17' 更改为 'January 13; 2018 04:17',稍后再担心转换。

我尝试过这样的表达方式:

'([^']*)'

它包含引号之间的所有内容,但我无法仅定位引号之间的逗号。

最佳答案

您可以首先用一些独特的名称替换有问题的逗号,然后以此分隔。最后,我们循环各个部分并实际构建我们的对象:

var subject = "type: 'click', category: 'REFRESH_DOOR', desc: 'clicked refresh from door 0124', site: 'mysite', pathname: '/load_areas/all/doors', params: '?sort_by=code&layout=view_by_4', time: '1515838628166', mobile: 'false', bp: 'xlarge', size: '[1920, 935]', area: 'all', sid: '15158225889', facility: 'MMMM', IP Address: 'XXX.XXX.XXX.XXX', created: 'January 13, 2018 04:17'";

var regex = /'[^']+'|(,)/g;
var kv = /(\w+):\s*'([^']+)'/;

replaced = subject.replace(regex, function(m, group1) {
if (typeof group1 == 'undefined') return m;
else return 'SUPERMAN';
});

// create an object that holds our values
var jsonObject = {};

// create a function that splits the individual items
function splitter(item) {
var match = kv.exec(item);
jsonObject[match[1]] = match[2];
}

parts = replaced.split("SUPERMAN");
parts.forEach(splitter);
console.log(jsonObject);
<小时/>其结果是:

{
"type": "click",
"category": "REFRESH_DOOR",
"desc": "clicked refresh from door 0124",
"site": "mysite",
"pathname": "/load_areas/all/doors",
"params": "?sort_by=code&layout=view_by_4",
"time": "1515838628166",
"mobile": "false",
"bp": "xlarge",
"size": "[1920, 935]",
"area": "all",
"sid": "15158225889",
"facility": "MMMM",
"Address": "XXX.XXX.XXX.XXX",
"created": "January 13, 2018 04:17"
}

<小时/>改编自 The Best Regex Trick .

关于javascript - JS 正则表达式匹配引号内的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48287527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com