【问题标题】:Regular Expression - Replace multiple lines w/ same number of blank lines正则表达式 - 用/相同数量的空行替换多行
【发布时间】:2019-03-04 01:01:54
【问题描述】:

是否可以使用正则表达式来替换具有相同数量的空行的多行?

在上下文中,我需要能够更改以下内容:

01    /*------------------------------------
02    Some history stuff goes here
03    Some history stuff goes here
04    Some history stuff goes here
05    Some history stuff goes here
06    Some history stuff goes here
07    --------------------------------------*/
08    int main void()
09    {
10       printf("Hello, World!");
11
12       return 0;
13    }

如下:

01    
02    
03    
04    
05    
06    
07    
08    int main void()
09    {
10       printf("Hello, World!");
11
12       return 0;
13    }

现在我只有以下正则表达式模式,但它只用一行替换了 01-07 行:

\/\*.*?\*\/
(. matches newline checked)

如果有帮助,我会使用 Notepad++ 的“在文件中查找”功能,因为我需要在文件夹中的多个文件中执行此操作。

【问题讨论】:

  • @sweaver2112 "ff" 是 "following" 的快捷方式
  • 你检查this了吗?
  • @STIKO 谢谢,但我并没有试图删除“空行”,而是试图用相同数量的“空白行”替换“块 cmets”
  • 我认为您需要一些脚本命令来完成这项工作,正则表达式在替换中不提供“匹配的行数”变量。
  • @sweaver2112 有什么开始的建议吗?

标签: regex notepad++


【解决方案1】:

由于您使用的是notpad++,我假设您使用的是 Windows。您可能需要使用 power shell 来实现这一点。 先逐行读取文件,发现here

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

然后在行以/*开始并以*/结束时做一些逻辑,源here

$Group.StartsWith("/*")

【讨论】:

    【解决方案2】:

    这个 perl 单行代码可以完成这项工作:

    perl -ne 'if (/\/\*/ .. /\*\//) {print "\n"} else {print}' file > output
    

    windows下,单引号换成双引号

    perl -ne "if (/\/\*/ .. /\*\//) {print \"\n\"} else {print}" file > output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多