MCPcopy Create free account
hub / github.com/Illusionna/LocalTransfer / FindStringWithContext

Function FindStringWithContext

utils.go:562–610  ·  view source on GitHub ↗

查找文件内容中目标字符串附近的上下文.

(filename string, str string)

Source from the content-addressed store, hash-verified

560
561// 查找文件内容中目标字符串附近的上下文.
562func FindStringWithContext(filename string, str string) ([]string, error) {
563 file, err := os.Open(filename)
564 if err != nil {
565 return nil, err
566 }
567 defer file.Close()
568
569 var results []string
570 scanner := bufio.NewScanner(file)
571 lineNumber := 0
572
573 for scanner.Scan() {
574 line := scanner.Text()
575 lineNumber++
576 index := strings.Index(line, str)
577 if index == -1 {
578 continue
579 }
580
581 // 转换为 rune 切片以处理多字节字符.
582 runes := []rune(line)
583 subRunes := []rune(str)
584 runesLen := len(runes)
585 subLen := len(subRunes)
586
587 // 遍历所有匹配位置.
588 for i := 0; i <= runesLen - subLen; i++ {
589 match := true
590 for j := 0; j < subLen; j++ {
591 if runes[i + j] != subRunes[j] {
592 match = false
593 break
594 }
595 }
596 if match {
597 start := max(0, i - 15)
598 end := min(runesLen, i + subLen + 15)
599 context := string(runes[start:end])
600 results = append(results, context)
601 i = i + subLen - 1 // 跳过已匹配部分.
602 }
603 }
604 }
605
606 if err := scanner.Err(); err != nil {
607 return nil, err
608 }
609 return results, nil
610}
611
612
613func SearchFile(selected_file FILE_SEARCH) []map[string]string {

Callers 1

SearchFileFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected