如何通过VS Code API获取正则匹配结果的行号与字符位置
解决方案
你可以直接调用VS Code API 内置的TextDocument.positionAt()方法实现需求,该方法可以将文档内容的全局字符偏移量转换为对应的行号与字符位置对象。
完整代码示例
const vscode = require('vscode') const editor = vscode.window.activeTextEditor if (editor) { const document = editor.document const text = document.getText() const match = text.match(/match/) if (match) { // match.index 是匹配内容在整个文档字符串中的起始偏移量 const startPos = document.positionAt(match.index) // 匹配内容的结束位置 const endPos = document.positionAt(match.index + match[0].length) // 行号从0开始计数,如果需要展示给用户的1开始行号,自行+1即可 const lineNumber = startPos.line const characterOffset = startPos.character console.log('匹配位置:行', lineNumber + 1, ',字符', characterOffset + 1) } }
注意事项
- 如果你需要匹配所有结果,不要使用
match加g修饰符的写法,这种写法返回的结果不会携带index属性,建议改用RegExp.exec()循环获取所有匹配项的偏移量。 - 拿到的
Position对象的line和character属性都是从0开始计数,如果需要和编辑器界面展示的1开始行号/列号对应,自行加1即可。
内容的提问来源于stack exchange,提问作者wyc
相关产品推荐
相关产品推荐

