Search code examples
regexnotepad++

How to Join Two Last Non-Empty Lines Before a Specific Pattern?


I have a list like following:

1.58%
0009
1991
/////////////////////////
Phil
ttr0018
1991
/////////////////////////

Now I want to join two last non-empty lines before ///////////////////////// lines like following (what output I want):

1.58%
0009 1991
/////////////////////////
Phil
ttr0018 1991
/////////////////////////

I tried following regex but not working:

Find : ^(\h*\S.*)(?=\R+(?:\h*\S.*\R+)?/{24})
Replace : \1

Where is problem?


Solution

  • Currently you are using a single match with a capture group in your regex, where the replacement with group 1 will give back the same result.

    What yo might do is use 2 capture groups, and replace with $1 $2

    ^(\h*\S.*)(?:\R\h*)*\R(\h*\S.*)(?:\R\h*)*(?=\R/{24})
    

    See a regex demo

    Or a bit shorter, using $1 $2\n in the replacement.

    ^(\h*\S.*)\R\s*^(\h*\S.*)\R\s*^(?=/{24})
    

    The pattern matches:

    • (\h*\S.*) Capture group 1, match optional leading horizontal whitespace chars, at least a non whitespace char and the rest of the line
    • \R\s*^ Match a newline, optional whitespace chars and assert the start of the string
    • (\h*\S.*) Capture group 2, same pattern as group 1
    • \R\s*^ Same as previous pattern
    • (?=/{24}) Positive lookahead, assert 24 times a / char

    See another regex demo

    enter image description here


    As a side note, using ^(\h*\S.*) can by itself also match only forward slashes.

    If you want to prevent that, you could use for example a negative lookahead to assert not 24 times a forward slash

    ^(?!/{24})