JS/node.js中匹配字符的行号

Mad*_*C.S 8 javascript regex node.js

是否可以在Javascript或node.js中找到多行输入(如文件)的正则表达式匹配字符的行号?

Sha*_*mal 7

如何通过字符串索引获取行号

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;
}
Run Code Online (Sandbox Code Playgroud)

这有什么用

创建一个返回第一个匹配的行号的函数

function lineNumber(needle,haystack){
    return lineNumberByIndex(haystack.indexOf(needle),haystack);
}
Run Code Online (Sandbox Code Playgroud)

创建一个返回每个匹配的行号的函数

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

小提琴


McK*_*yla 6

是的,有一个半尴尬的工作.

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;
});
Run Code Online (Sandbox Code Playgroud)


Eli*_*rer 6

谢谢@Shanimal,我更改了您的代码以添加列位置:

function lineNumberByIndex(index, string) {
  const re = /^[\S\s]/gm;
  let line = 0,
    match;
  let lastRowIndex = 0;
  while ((match = re.exec(string))) {
    if (match.index > index) break;
    lastRowIndex = match.index;
    line++;
  }
  return [Math.max(line - 1, 0), lastRowIndex];
}

const findOccurrences = (needle, haystack) => {
  let match;
  const result = [];
  while ((match = needle.exec(haystack))) {
    const pos = lineNumberByIndex(needle.lastIndex, haystack);
    result.push({
      match,
      lineNumber: pos[0],
      column: needle.lastIndex - pos[1] - match[0].length
    });
  }
  return result;
};

const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.`;
findOccurrences(/dolor/gim, text).forEach(result =>
  console.log(
    `Found: ${result.match[0]} at ${result.lineNumber}:${result.column}`
  )
);
Run Code Online (Sandbox Code Playgroud)