( messages: ChatMessage[], query: string, options: SearchOptions )
| 44 | * 在消息列表中查找所有匹配项 |
| 45 | */ |
| 46 | export function findAllMatches( |
| 47 | messages: ChatMessage[], |
| 48 | query: string, |
| 49 | options: SearchOptions |
| 50 | ): SearchMatch[] { |
| 51 | const pattern = createSearchPattern(query, options) |
| 52 | if (!pattern) return [] |
| 53 | |
| 54 | const matches: SearchMatch[] = [] |
| 55 | let globalIndex = 0 |
| 56 | |
| 57 | for (const message of messages) { |
| 58 | const content = message.content |
| 59 | let match: RegExpExecArray | null |
| 60 | |
| 61 | // 重置 lastIndex |
| 62 | pattern.lastIndex = 0 |
| 63 | |
| 64 | while ((match = pattern.exec(content)) !== null) { |
| 65 | matches.push({ |
| 66 | messageId: message.id, |
| 67 | startOffset: match.index, |
| 68 | endOffset: match.index + match[0].length, |
| 69 | globalIndex: globalIndex++ |
| 70 | }) |
| 71 | |
| 72 | // 防止零长度匹配导致无限循环 |
| 73 | if (match[0].length === 0) { |
| 74 | pattern.lastIndex++ |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | return matches |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * 验证正则表达式是否有效 |
no test coverage detected