gpt4 book ai didi

javascript - 用于解析 OpenEdge 数据导出中带引号的字符串的正则表达式

转载 作者:行者123 更新时间:2023-12-03 06:10:21 25 4
gpt4 key购买 nike

我有一个来自 Progress OpenEdge 系统的数据导出,我想用 JavaScript 进行解析。我想使用正则表达式查找导出的所有字段。

我尝试过很多与此类似的事情: /("[^"]*")|[^\s]+/g 我也尝试过使用负向预测 (?!"") 但到目前为止我还没有成功。

示例导出输出可能类似于以下内容:

12345 24,25 0 2015-06-30T14:53:14.891 "12345" "24,25" "0" "2015-06-30T14:53:14.891" "" yes no ? "String with ""quoted"" word" "String 
with a multi
line string. "" <- Just a quote
" " This is the last value "
6789 35,36 0 2016-07-31T15:54:15.892 "6789" "35,36" "0" "2016-07-31T15:54:15.892" "" no yes ? "Just a simple string" ? ?

字段是:

DEFINE TEMP-TABLE tt_test NO-UNDO
FIELD valueA AS INTEGER
FIELD valueB AS DECIMAL
FIELD valueC AS INTEGER
FIELD valueD AS DATETIME
FIELD valueE AS CHARACTER
FIELD valueF AS CHARACTER
FIELD valueG AS CHARACTER
FIELD valueH AS CHARACTER
FIELD valueI AS CHARACTER
FIELD valueJ AS LOGICAL
FIELD valueK AS LOGICAL
FIELD valueL AS LOGICAL
FIELD valueM AS CHARACTER
FIELD valueN AS CHARACTER
FIELD valueO AS CHARACTER
.

导出格式为:所有字段均以空格分隔。字符串包含在双引号字符 (") 内。如果字符串中存在引号,则使用两个双引号字符 ("") 进行转义。如果存在空字符串,该字符串也是两个双引号字符 ( ""),但周围有分隔符空格。

实际的数据类型以及这是一个进度系统​​这一事实并不重要,这只是为我的问题提供一些背景。

总结一下:如何编写一个(JavaScript 兼容)正则表达式来成功分隔导出数据的不同部分,同时忽略字符串中转义的双引号?

最佳答案

我认为仅用一个正则表达式是不可能做到这一点的。这里你需要一个解析器。幸运的是,它很容易编写,例如:

str = `12345 24,25 0 2015-06-30T14:53:14.891 "12345" "24,25" "0" "2015-06-30T14:53:14.891" "" yes no ? "String with ""quoted"" word" "String
with a multi
line string. "" <- Just a quote
" " This is the last value "
6789 35,36 0 2016-07-31T15:54:15.892 "6789" "35,36" "0" "2016-07-31T15:54:15.892" "" no yes ? "Just a simple string" ? ?`;

str = str.replace(/""/g, '@');

matches = str.match(/"([\s\S]*?)"|\S+|\n/g);

rows = [[]]

for(var m of matches) {
if (m === '\n') {
rows.push([]);
continue;
}
if(m === '@') {
m = '';
}
if (m[0] === '"') {
m = m.slice(1, -1);
}
m = m.replace(/@/g, '"');
rows[rows.length - 1].push(m)
}

console.log(rows)

关于javascript - 用于解析 OpenEdge 数据导出中带引号的字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39345388/

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