如何使用正则表达式在记事本++中缩进代码 [英] How to use regex to indent code in notepad++

查看:60
本文介绍了如何使用正则表达式在记事本++中缩进代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有以下代码

Module MPI
    Use MPI
    !
! MPI info
    If (true) Then
        Print *, ''
! empty line 1
! empty line 2
    End If
    Integer ithread, nthread, ierr
End Module MPI

这些行以 ! 符号开始,这是 Fortran 中的注释行.我希望这些注释行的缩进与其前一行的缩进相同.

The lines start with ! sign which is comment lines in fortran. I want those comment lines have the same indent as their previous line indent.

我想要这个格式

Module MPI
    Use MPI
    !
    ! MPI info
    If (true) Then
        Print *, ''
        ! empty line 1
        ! empty line 2
    End If
    Integer ithread, nthread, ierr
End Module MPI

我想使用正则表达式在记事本++中执行此操作.但如果有更好的选择,请随时回答.

I want to do this in notepad++ using regex. But if there are better choice feel free to answer.

这是我尝试过的:将 ^(\s*)(.*?\r\n)\s*\! 替换为 $1$2$1!.然而它产生

Here is what I have tried: replace ^(\s*)(.*?\r\n)\s*\! as $1$2$1!. However it produce

Module MPI
    Use MPI
    !
! MPI info
    If (true) Then
        Print *, ''
        ! empty line 1
! empty line 2
    End If
    Integer ithread, nthread, ierr
End Module MPI

还有两行不对.看起来虽然模式 ^(\s*)(.*?\r\n)\s*\! 匹配这一行,但是,它只是跳过它,因为正则表达式引擎已经匹配上一个线.

There is still two lines not right. It seems that though the pattern ^(\s*)(.*?\r\n)\s*\! matches this line, however, it just skip it for the regex engine already matched previous lines.

我的问题是如何用正则表达式解决这个缩进问题?

推荐答案

使用搜索文本 ^( +)(.*\R)(!) 和替换文本 \1\2\1\3 然后单击全部替换"两次即可完成示例文本所需的操作.我看不到一次通过的方法.

Using the search text ^( +)(.*\R)(!) and the replace text \1\2\1\3 then clicking on "Replace all" twice does what is wanted on the sample text. I cannot see a way of doing this in one pass.

该表达式查找带有前导空格的行,后跟以 ! 开头的行.捕获组是 \1 中的前导空格,该行的其余部分包括 \2 中的换行符和 ! 中的前导 !>\3.替换只是按正确的顺序组合捕获.请注意,您可以省略 ! 周围的捕获组,只需要一个显式的 `!在替换中,但我喜欢在这种情况下使用捕获,因为它们通常允许更短的替换(尽管在这种情况下不是)和更容易的增强.

The expression looks for a line with leading spaces followed by a line starting with a !. The capture groups are the leading spaces in \1, the rest of that line including the newline in \2 and the leading ! in \3. The replacement just assembles the captures in the right order. Note that you could omit the capture group around the ! and just have an explicit `! in the replacement, but I like to use captures in such contexts as they often allow for shorter replacements (although not in this case) and easier enhancements.

这篇关于如何使用正则表达式在记事本++中缩进代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆