Search code examples
regexsublimetext3

Match characters across line in different blocks in Sublime


Suppose I have a text file like below:

Block 1 start
Line 1 in Block 1
Line 2 in Block 1
Block 1 end

Block 2 start
Line 1 in Block 2

Block 3 start
Line 1 in Block 3
Block 3 end

How can I select Block 1 and Block 3 (start and end lines inclusive) and skip the two lines of Blocks 2 in Sublime?


Solution

  • (?s)Block (\d+) start.+Block \1 end
    

    Example

    (?s)              - basically a multiline modifier. Allows the `.` to match newlines.
    Block (\d+) start - Matches the start of a block
    .+                - Capture everything inside the block
    Block \1 end      - Finds the end of the block by using the number found at the beginning in the Block start section.(back referencing)
    

    This should work for cases where you want to skip blocks that don't have a valid end section.

    If the data isn't well formatted, then you will run into issues. For an example if something like Block 1 end happens to be inside the block.