javascript - 您如何将一组行组合到另一个数组中,其中未标记的行与前一行组合?
问题描述
我有一个多行注释,其中某些行带有标签。
例如:
[
'Label1: this is the first line',
'Label2: this is the second line',
'this is the third line',
'this is the fourth line',
'Label3: this is the fifth line' ]
我想压缩这个数组,以便在一行没有标签时识别它,它附加到最后一行有标签的行。
期望的结果:
[
'Label1: this is the first line',
'Label2: this is the second line \n this is the third line \n this is the fourth line',
'Label3: this is the fifth line' ]
我正在尝试一个双循环,但它正在识别没有用当前索引标记的行。
else if (!isLineLabeled(lines[j+1], labels[i])){
}
function isLineLabeled(line, label) {
return line.trim().toLowerCase().startsWith(label.toLowerCase());
}
function combineLines(lines) {
let arr = [];
const labels = ['Label1', 'Label2', 'Label3'];
for (let i = 0; i < labels.length; i++) {
for (let j = 0; j < lines.length; j++) {
if (isLineLabeled(lines[j], labels[i])) {
linesObj.push(lines[j]);
}
}
}
return arr;
}
解决方案
如果您对正则表达式不满意,这里有一个没有它的函数(我使用列表而不是数组,但您发现了偏差)...
public static List<string> GetLabelledList(List<string> list){
var returnList = new List<string>();
var currentString = string.Empty;
foreach(var s in list){
if(!s.StartsWith("Label")) {
if(currentString != string.Empty){
currentString += " \n ";
}
currentString += s;
}else{
if(currentString != string.Empty){
returnList.Add(currentString);
}
currentString = s;
}
}
if(currentString != string.Empty){
returnList.Add(currentString);
}
return returnList;
}
推荐阅读
- c# - 如果 TextBox 有 8 个字符 xaml C#,则将其清除
- python - 导入 XLUtils 时出现 ModuleNotFoundError 错误
- python - 使用 cURL 和烧瓶更新网页
- ios - 按月份对 NSSortDescriptor 进行排序。迅速
- javascript - Audiomack 嵌入在移动设备上没有响应
- python - 无法通过python连接mysql
- javascript - 如何在反应中获取 api 对象属性
- junit - 用于全局 java.util.Map 的 Junit Mockito
- python - Python openpyxl 条件格式 containsText
- excel - ag-Grid 使用 Angular 9 材料组件模拟 Excel