如何从这个字符串中提取单个值?

时间:2017-04-04 04:14:02

标签: javascript regex

在javascript中,我有这个输入

'Templeton Primary School,Wantirna,VIC,3152\r\n                                    \r\n                                        3152\r\n                                    \r\n                                        98\r\n                                    \r\n                                        \r\n                                    \r\n                                        \r\n                                    696'

所以从上面的输入中我会得到:

地址:Templeton,Wantirna,3152,Templeton小学

邮政编码:3152

得分:98

enrolNum:696

我有这样的事情:/(.+)(\\r\\n *)+(.+)(\\r\\n *)+(.+)(\\r\\n *)+(.+)/g

显然,它不起作用。

4 个答案:

答案 0 :(得分:0)

尝试将字符串拆分为数组,然后您可以访问所需的特定部分。

var theList = your input data;
var address = theList.split(',');
var zip = address[3];

另外,您的表单如何设置以收集此数据?一个文本框是一个糟糕的设计。尝试将字段拆分为单独的文本框。

答案 1 :(得分:0)

你可以试试这个:

^(.*?)\D+(\d+)[\D]+(\d+)\D+(\d+)$

Demo

const regex = /^(.*?)\D+(\d+)[\D]+(\d+)\D+(\d+)$/gm;
const str = `Templeton Primary School,Wantirna,VIC,3152\\r\\n                                    \\r\\n                                        3152\\r\\n                                    \\r\\n                                        98\\r\\n                                    \\r\\n                                        \\r\\n                                    \\r\\n                                        \\r\\n                                    696`;
let m;

while ((m = regex.exec(str)) !== null) {
    console.log("address: "+m[1]);
    console.log("postcode: "+m[2]);
    console.log("score: "+m[3]);
    console.log("enroll number: "+m[4]);
}

答案 2 :(得分:0)

var input= '''INPUT GOES HERE''';
var inputList = input.split('\\r\\n');
var address = inputList[0].trim();
var postcode = inputList[1].trim();
.
.
.

答案 3 :(得分:0)

var str = 'Templeton Primary School,Wantirna,VIC,3152\r\n                                    \r\n                                        3152\r\n                                    \r\n                                        98\r\n                                    \r\n                                        \r\n                                    \r\n                                        \r\n                                    696'
var arr = str.split(',');

arr = arr.concat(/(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$/.exec(arr.pop()).slice(1));

console.log( arr )

var result = {
    address : arr.slice(0,4).join(','),
    postcode: arr[4],
    score   : arr[5],
    enrolNum: arr[6]
};

console.log(result)