You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中IndexOf()传双参数报错,匹配重载仍无法运行?

PowerShell 解决方案

问题根源

你的脚本存在两个核心问题:

  • Get-Content 默认返回字符串数组(每行一个元素),数组的 IndexOf 方法不支持双参数重载,这是报错的直接原因;同时数组形式无法处理跨多行的文本匹配。
  • 你需要定位起始标记之后最后一个 */,应该用 LastIndexOf 而非 IndexOf,否则只会找到第一个匹配项。

修正后的脚本

# 读取文件为单个完整字符串(-Raw 参数是关键)
$fileContent = Get-Content -Path "file/to/be/read" -Raw
$searchString = "/* original invocation */"

# 获取起始标记的索引
$startIndex = $fileContent.IndexOf($searchString)
if ($startIndex -eq -1) {
    Write-Host "未找到起始标记"
    exit
}

# 计算起始标记的结束位置(跳过起始字符串本身)
$startPosition = $startIndex + $searchString.Length

# 找到起始位置之后最后一个 "*/" 的索引
$endIndex = $fileContent.LastIndexOf("*/")
if ($endIndex -eq -1) {
    Write-Host "未找到结束标记"
    exit
}

# 提取目标文本(+2 是为了包含结束标记 "*/")
$extractedText = $fileContent.Substring($startPosition, $endIndex - $startPosition + 2)

# 保存到目标文件
$extractedText | Out-File -Path "path/to/save/result.txt" -Encoding utf8
Python 解决方案

Python 实现更简洁,提供两种可选方式:

方式1:基础字符串方法

with open("file/to/be/read", "r", encoding="utf-8") as f:
    content = f.read()

start_str = "/* original invocation */"
start_idx = content.find(start_str)
if start_idx == -1:
    print("未找到起始标记")
    exit()

# 跳过起始字符串,定位到内容起始点
start_pos = start_idx + len(start_str)
# 查找最后一个结束标记的位置
end_idx = content.rfind("*/")
if end_idx == -1:
    print("未找到结束标记")
    exit()

# 提取完整目标文本(包含结束标记)
extracted = content[start_pos:end_idx+2]

# 写入结果文件
with open("path/to/save/result.txt", "w", encoding="utf-8") as f:
    f.write(extracted)

方式2:正则表达式(适配复杂场景)

import re

with open("file/to/be/read", "r", encoding="utf-8") as f:
    content = f.read()

# 匹配从起始标记到最后一个结束标记的完整内容
pattern = re.compile(r'/\* original invocation \*/(.*?)\*/', re.DOTALL)
match_result = pattern.search(content)

if match_result:
    # 拼接完整的文本块
    extracted = f"/* original invocation */{match_result.group(1)}*/"
    with open("path/to/save/result.txt", "w", encoding="utf-8") as f:
        f.write(extracted)
else:
    print("未找到目标文本块")

内容的提问来源于stack exchange,提问作者cfraser17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:25:22