Line number of matching characters in JS / node.js

Is it possible to find the line number of matching regular expression characters for multi-line inputs (e.g. files) in Javascript or node.js?

+7
source share
5 answers

Yes, with semi-elastic work.

http://jsfiddle.net/tylermwashburn/rbbqn/

var string = "This\nstring\nhas\nmultiple\nlines.",
    astring = string.split('\n'),
    match = /has/, foundon;

Array.each(astring, function (line, number) {
    if (match.exec(line))
        foundon = number + 1;
});
+6
source

It might be a good idea to use a parser generator. Zach Carter jison reports line numbers. Here is an example of a small utility that uses jison to parse JSON and reports errors with line numbers. This could be a good starting point.

https://github.com/zaach/jsonlint

exec (/myregex/.exec(mystring).index), (mystring.substring(0, index)), .

+3

function lineNumberByIndex(index,string){
    // RegExp
    var line = 0,
        match,
        re = /(^)[\S\s]/gm;
    while (match = re.exec(string)) {
        if(match.index > index)
            break;
        line++;
    }
    return line;
}

,

function lineNumber(needle,haystack){
    return lineNumberByIndex(haystack.indexOf(needle),haystack);
}

,

function lineNumbers(needle,haystack){
    if(needle !== ""){
        var i = 0,a=[],index=-1;
        while((index=haystack.indexOf(needle, index+1)) != -1){
            a.push(lineNumberByIndex(index,haystack));
        }
        return a;
    }
}

Fiddle

+2

, -

var text="aaaaaaaaaaaaaaaaaaaaa\naaaaaaaabaaaaaaaaaa\naaaaaaaaaaaaaaaaaaa";
var RE=/b/g
var until=text.split(RE)
if (until.length>1){//found
   var linenumber=until[0].split(/\n/g).length
}
0

match , , , match.

/**
 * Return the line number of the match, or -1 if there is no match.
 */
function matchLineNumber(m) {
  if (!m) {
    return -1
  }
  let line = 1
  for (let i = 0; i < m.index; i++) {
    if (m.input[i] == '\n') {
      line++;
    }
  }
  return line
}


const rx = /foo/
const ex1 = 'foo'
const ex2 = '
hello
foo
'
const ex3 = '
hello
'

console.log(matchLineNumber(rx.exec(ex1)))
console.log(matchLineNumber(rx.exec(ex2)))
console.log(matchLineNumber(rx.exec(ex3)))
Hide result

0