我有一个像这样的字符串
4741:GREEN,CIRHOSIS,ORANGE,Long-term,GREEN,HIS B CHIC,4642:GREEN,CRHOSIS,GREEN,HSysk B CC,
sting包含两个记录ID为4741和4642的记录。同样在记录中,其他所有内容都以逗号(,)
分隔我怎么能分开这个刺痛。请注意,此示例字符串仅包含2条记录,但其他记录可能包含更多或更少或没有。 谢谢你的帮助!
答案 0 :(得分:3)
基本理念:
var str = "4741:GREEN,CIRHOSIS,ORANGE,Long-term,GREEN,HIS B CHIC,4642:GREEN,CRHOSIS,GREEN,HSysk B CC,1111:asdf"
var re = /(\d+):([^(\d+:)]+)/g;
var matches = str.match(re);
for(var x in matches){
var parts = matches[x].split(":");
var id = parts[0];
var vals = parts[1].split(",");
alert(id + "\n" + vals.length);
}
答案 1 :(得分:2)
使用此:
var source = "4741:GREEN,CIRHOSIS,ORANGE,Long-term,GREEN,HIS B CHIC,4642:GREEN,CRHOSIS,GREEN,HSysk B CC,4643:GREEN,CRHOSIS,GREEN,HSysk B CC,4644:GREEN,CRHOSIS,GREEN,HSysk B CC,4645:GREEN,CRHOSIS,GREEN,HSysk B CC,4646:GREEN,CRHOSIS,GREEN,HSysk B CC,";
var extractRecordsAsArray = function (source) {
var records = [];
if (source && source.split) { // is string
var re = new RegExp("[0-9]+:[^0-9:]+", "g");
var entries = source.match(re);
for (var i = 0, len = entries.length; i < len; i++) {
var entry = entries[i].split(':');
records.push([entry[0], entry[1].split(',')]);
}
}
return (records);
};
console.log("records: %o", extractRecordsAsArray(source));
或者,如果您更喜欢存储地图:
var extractRecordsAsMap = function (source) {
var records = {};
if (source && source.split) { // is string
var re = new RegExp("[0-9]+:[^0-9:]+", "g");
var entries = source.match(re);
for (var i = 0, len = entries.length; i < len; i++) {
var entry = entries[i].split(':');
records[entry[0]] = entry[1].split(',');
}
}
return (records);
};
console.log("records: %o", extractRecordsAsMap(source));
不保证防弹并且效率最高,但是对于相当大的字符串会获得不错的性能并且工作正常。
答案 2 :(得分:0)
function split(str) {
var split = str.split(/,?(\w+):/);
var result = {};
for (var i = 1; i < split.length; i+=2) {
result[split[i]] = split[i+1].split(/,/);
}
return result;
}
split("4741:GREEN,CIRHOSIS,ORANGE,Long-term,GREEN,HIS B CHIC,4642:GREEN,CRHOSIS,GREEN,HSysk B CC");
// => {'4642': ['GREEN', 'CRHOSIS', 'GREEN', 'HSysk B CC'], '4741': ['GREEN', 'CIRHOSIS', 'ORANGE', 'Long-term', 'GREEN', 'HIS B CHIC']}
答案 3 :(得分:0)
您可以使用String.match函数:
var records = "4741:GREEN,CIRHOSIS,ORANGE,Long-term,GREEN,HIS B CHIC,4642:GREEN,CRHOSIS,GREEN,HSysk B CC,"
var regex = /[0-9]+:([a-zA-Z0-9]*,)+/gi;
records.match(regex);
结果:
["4741:GREEN,CIRHOSIS,ORANGE,", "4642:GREEN,CRHOSIS,GREEN,"]
如果您正在寻找更具体的内容,则需要延长您的问题。
另一个有趣的事情可能是在字符串中添加大括号,括号和引号,然后是JSON.parse()它。