我的JSON数据在
之下{
"response_code": 200,
"train": [
"19005 (SAURASHTRA MAIL)",
"19066 (BGKT BDTS EXP)"
],
"total": 2 }
其他格式低于相同数据
{
"response_code": 200,
"train": [
"(SAURASHTRA MAIL) (19005)",
"(BGKT BDTS EXP) (19066)"
],
"total": 2 }
从以上两种格式我想分开 19005 &两个值 SAURASHTRA MAIL 和弹出警报消息。
如何拆分?请帮忙
答案 0 :(得分:3)
您可以使用正则表达式并在级联中执行匹配。结果是一个包含整个结果和拆分值的数组。
var train = [
"19005 (SAURASHTRA MAIL)",
"19066 (BGKT BDTS EXP)",
"(SAURASHTRA MAIL) (19005)",
"(BGKT BDTS EXP) (19066)"
];
train.forEach(function (a) {
var m = a.match(/\((.*)\) \((.*)\)/);
if (m) {
console.log('1number: ' + m[2]);
console.log('1string: ' + m[1]);
return;
}
m = a.match(/(.*) \((.*)\)/);
if (m) {
console.log('2number: ' + m[1]);
console.log('2string: ' + m[2]);
}
});

答案 1 :(得分:0)
var str1 = "19005 (SAURASHTRA MAIL)";
var train_name1= str1.match(/\((.*?)\)/)[1];
var train_number1 = str1.match(/\d+/g);
var str2 = "(SAURASHTRA MAIL) (19005)";
var train_name2= str2.match(/\((.*?)\)/)[1];
var train_number2 = str2.match(/\d+/g);
alert("TRAIN NAME 1 : "+train_name2 +" AND TRAIN NUMBER : "+ train_number2 +", TRAIN NAME 2 : "+train_name2 +" AND TRAIN NUMBER : "+ train_number2);
答案 2 :(得分:0)
我写了这个正则表达式,它似乎做了你想要的
https://regex101.com/r/cD0uC8/1
\"\((.*)?\)\s*\((\d*)\)\"|\"(\d*)\s*\((.*)?\)\"/g
'/ g'是将正则表达式应用于所有行的修饰符