How to use regex for padding in pad ++

for example i have the following code

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 

Lines begin with a character ! , which is the comment line in fortran. I want the comment lines to have the same indentation as the previous line indentation.

That is, I want this format

 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 is a better choice, feel free to answer.

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

 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 

Still two lines are not correct. It seems that although the pattern is ^(\s*)(.*?\r\n)\s*\! matches this line, it just skips it so that the regex engine already matches the previous lines.

My question is how to solve this regex indented problem?

0
regex
source share
2 answers

Using the search text ^( +)(.*\R)(!) And replace the text \1\2\1\3 , then click "Replace All" twice, which is required for the sample text. I see no way to do this in one go.

The expression searches for a line with leading spaces, followed by a line starting with ! . Capture groups are leading spaces in \1 , the rest of this line includes a new line in \2 and leading ! in \3 . A replacement only collects the captures in the correct order. Note that you can omit the capture group around ! and just have an explicit `! in substitution, but I like to use captures in such contexts, as they often allow shorter replacements (although not in this case) and easier improvements.

+3
source share

Since the engine is already passed in the comment line for indentation, I think it’s impossible to use the same whole line edited for the next match to get the number of spaces. Therefore, I think you need to repeat the same replacement more than once. Try:

 ^(\s*)([^!\s].*?\r\n(\1\!.*?\r\n)*)\s*\! 

always replacing it with $1$2$1! .

As I said in the comment, if you have no more than N consecutive comment lines, you will click on the “replace all” button N times

+1
source share

All Articles