本文旨在提供一个解决方案,用于将程序输出中的相对或绝对文件路径转换为带有行号的可点击链接(例如 `src:///path/to/file:43`)。通过结合
正则表达式
匹配和文件存在性验证,可以实现一个相对健壮的路径转换工具,尤其适用于编程环境。
在开发过程中,我们经常需要从编译器的输出或其他程序的日志中定位到特定的文件和行号。为了方便跳转,可以将这些路径转换为可点击的链接。本文将介绍如何使用正则表达式和文件存在性检测来实现这一目标。
核心思路
核心思路是使用正则表达式从文本中提取潜在的文件路径和行号,然后验证这些路径的有效性,最后将其转换为特定格式的链接。
正则表达式匹配
由于文件名的格式具有一定的自由度,因此我们需要选择一个合适的正则表达式来匹配常见的编程文件路径。以下是一个推荐的正则表达式,它可以匹配包含字母、数字、下划线、点、斜杠和连字符的文件路径,并捕获文件名和行号:
这个正则表达式的解释如下:
(?
输出:
(?package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
text := `
./test.go:3931: undefined: erre
/path/to/file.txt:123: some error
invalid-path:abc:456
`
re := regexp.MustCompile(`(?m)(?File: ./test.go, Line: 3931
File: /path/to/file.txt, Line: 123package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
)
func main() {
text := `
./test.go:3931: undefined: erre
/path/to/file.txt:123: some error
`
re := regexp.MustCompile(`(?m)(?package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
)
func main() {
text := `
./test.go:3931: undefined: erre
/path/to/file.txt:123: some error
`
re := regexp.MustCompile(`(?m)(?src:///your/absolute/path/test.go:3931
src:///your/absolute/path/file.txt:123