从给定字符串中找到行号

时间:2017-02-27 05:48:30

标签: javascript regex parsing

我想从下面的字符串中获取行号。我尝试了以下来获取行号但看起来不可靠

string.split('Line')[1].split(':')[0]

字符串:

"Line 30:6 Table not found 'users'"

输出:

{ line: 30, statement: "Table not found 'users'" }

2 个答案:

答案 0 :(得分:0)

var x = "Line 30:6 Table not found 'users'";
y = x.split(":");

var newObj = {
  line : y[0].split(" ")[1],
  data : y[1].substr(2)
}

console.log(newObj);

答案 1 :(得分:0)

您可以使用Regular Expression从字符串中提取数据。

示例:下面的extract()函数将完成工作

var regex =  /^Line ([0-9]+):[0-9]+ (.*)$/g

function extract(str){
    var result = regex.exec(str);
    if(result != null){
        return {
            "line": result[1],
            "data": result[2]
        }
    }else{
        return null;
    }
}


var input = "Line 30:6 Table not found 'users'";
var output = extract(input);