[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[问题求助] [已解决]用powershell正则在特定行后追加多行

本帖最后由 小白龙 于 2023-5-3 10:22 编辑

我想在最后一个using开头的行后追加两行文本, 下面的代码没有效果, 求路过大佬指正
原文本:

using System.forms;
using System;

public class cla
{
        public string hello()
        {
                return "hello";
        }
}
最后需要的结果
using System.forms;
using System;
using System.IO;
using System.Text;


public class cla
{
        public string hello()
        {
                return "hello";
        }
}
  1. $content = @'
  2. using System.forms;
  3. using System;
  4. public class cla
  5. {
  6. public string hello()
  7. {
  8. return "hello";
  9. }
  10. }
  11. '@
  12. $pattern = '(using\s+.+;)(?=(?:[^{}]*{[^{}]*})*[^{}]*$)'
  13. $replacement = '$&' + "`r`nusing System.IO;" + "`r`nusing System.Text;"
  14. $result = [regex]::Replace($content, $pattern, $replacement)
  15. $filePath = "$HOME\Desktop\a.txt"
  16. Set-Content -Path $filePath -Value $result
复制代码
1

评分人数

    • Batcher: 感谢给帖子标题标注[已解决]字样PB + 2

虽然看不懂ps代码 但是如果是我 我会先定位到最后一个using的行数 在把文本分割成一行一行的数组 再拼接 插入(我这肯定不是最好的办法)

TOP

  1. $content = @'
  2. using System.forms;
  3. using System;
  4. public class cla
  5. {
  6. public string hello()
  7. {
  8. return "hello";
  9. }
  10. }
  11. '@
  12. $append = @'
  13. using System.IO;
  14. using System.Text;
  15. '@
  16. $result = $content -replace '^(.|\r|\n)*\n\s*using\s+\w+.*?\n', ('$0' + $append + "`n")
  17. $filePath = "$HOME\Desktop\a.txt"
  18. Set-Content -Path $filePath -Value $result
复制代码
1

评分人数

TOP

直接$append+$content呗
没必要非要加在后面吧,$append后面加个换行就行

TOP

回复 4# pd1


    多谢关注, 主要是想研究一下正则

TOP

本帖最后由 newswan 于 2023-5-3 14:32 编辑
  1. $content -replace "(?<=using.*`n)(?=`n)","$append`n"
复制代码
你的示例是 字符串, 如果是字符串数组,又不一样了.

TOP

返回列表