LoginSignup
1
0

More than 5 years have passed since last update.

Regexの結果から、行番号を計算する

Posted at

やりたいこと

  • 正規表現でマッチした場所の行番号が知りたい

やり方

下記のようにすればおk。execは、マッチ箇所を全て舐め終わるとnullを返すので便利です。

function getLine(fileContent, matchIndex) {
  let indexCount = 0;
  let lineNumber = 0;
  const lines = fileContent.split('¥n');
  for (const line of lines) {
    lineNumber++;
    indexCount += line.length + 1; // 改行コード分
    if (matchIndex < indexCount) { // マッチした場所が見つかった
      break;
    }
  }
  return lineNumber;
}

const fileContent = ...;
const reg = /.../g;

const matchData = reg.exec(reg);
const lineNumber = getLine(fileContent, matchData.index);
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0