我有一些数据需要转换为数组,但我无法使正则表达式工作得很好。我只需要一个一维数组,不需要数字,只需要值 - 但是带有换行符的项目会弄乱它。
正则表达式:([0-9]\-\ )(.*)([\s]*)
测试:https://regex101.com/r/F9UIG8/1
数据:
1- TEST DATA.
1- TEST DATA THAT GOES ONTO
TWO LINES.
2- MORE TESTS.
1- ADDITIONAL MULTILINE
DATA WITH
SEVERAL LINES
3- MORE TEST 3
4- MORE TEST 4
1- MORE SUB ITEMS
2- SUB ITEM 2
3- SUB ITEM MULTILINE
SECOND LINE
4- MORE
2- EVEN MORE TWO LINE
SECOND LINE
1- DATA
2- DATA
3- DATA
4- DATA TWO LINE
2ND LINE.
3- LAST BIT OF 2 LINE DATA
WITH SECOND LINE
答案 0 :(得分:0)
使用split()
方法尝试此正则表达式:
let text = `1- TEST DATA.
1- TEST DATA THAT GOES ONTO
TWO LINES.
2- MORE TESTS.
1- ADDITIONAL MULTILINE
DATA WITH
SEVERAL LINES
3- MORE TEST 3
4- MORE TEST 4
1- MORE SUB ITEMS
2- SUB ITEM 2
3- SUB ITEM MULTILINE
SECOND LINE
4- MORE
2- EVEN MORE TWO LINE
SECOND LINE
1- DATA
2- DATA
3- DATA
4- DATA TWO LINE
2ND LINE.
3- LAST BIT OF 2 LINE DATA`;
text.split(/\s*\d\-/igm);
它将返回一个带有文本的数组(包括换行符),删除数字和超量。
答案 1 :(得分:0)
感谢您的帮助,我使用@ncardeli的答案变体将其构建到Google应用程序脚本中。
function JSONIFYRANGE(range, asJSON){
var array = new Array();
for (var i = 0; i < range.length; i++) {
array.push({name: range[i][0], items: JSONIFY(range[i][1], asJSON)});
}
return JSON.stringify(array);
}
function JSONIFY(input, asJSON) {
if(input.indexOf("[ ]") >= 0 || input.indexOf("[ ]") >= 0 || input.indexOf("[ ]") >= 0){
return JSONIFY2(input, asJSON);
} else {
return JSONIFY1(input, asJSON);
}
}
function JSONIFY1(input, asJSON) {
var json = input.split(/\s*\d\-/igm); // answer from @ncardeli
var newArray = new Array();
for (var i = 0; i < json.length; i++) {
if (json[i] != "") {
newArray.push(json[i].replace("SOME COMMON TEXT I DONT WANT IN THE ITEMS", "").trim());
}
}
return asJSON ? newArray : JSON.stringify(newArray);
}
function JSONIFY2(input, asJSON) {
var json = input.split(/\s*\[\s*\]/igm);
var newArray = new Array();
for (var i = 0; i < json.length; i++) {
if (json[i] != "") {
newArray.push(json[i].trim());
}
}
return asJSON ? newArray : JSON.stringify(newArray);
}
使用它像:=JSONIFYRANGE('Items'!B2:C40, true)
其中B列保存列表名称,C列保存要拆分为项目的字符串,输出带有以下签名的JSON字符串:
{[
{
name: "List 1 Name",
items: [
"TEST DATA THAT GOES INTO TWO LINES",
"MORE TESTS.",
...
]
},
{
name: "List 2 name",
items: [
"SOME ITEM",
"SOME OTHER ITEM",
...
]
},
...
]}