Search code examples
regexvim

Regex distinguish < in logical operations and parenthesis pairs


I am coding a plugin that automatically adds spaces around symbols, I use the search function to locate symbols that match the regular expression and then modify. But I can't write an expression to distinguish the < in

#include<stdio.h>
a<b
a<b>
a<v and c>d

it should be

#include<stdio.h>
a < b
a<b>
a < v and c > d

but it will be

#include < stdio.h>
a < b
a < b>
a < v and c > d

I would be very grateful if you could help me write this expression.

Thanks.

I used [^ <']<[^ <='] for search the <, but obviously this doesn't work.


Solution

  • If lookarounds are supported, you could use

    (?<!\S)([^\s<>+])([<>])([^\s<>]+)(?!\S)
    

    The pattern matches:

    • (?<!\S) Assert a whitespace boundary to the left
    • ([^\s<>+]) Capture group 1, match 1+ non whitespace chars other than < >
    • ([<>]) Capture group 2, capture either < or >
    • ([^\s<>]+) Capture group 3, match 1+ non whitespace chars other than < >
    • (?!\S) Assert a whitespace boundary to the right

    Regex demo

    In the replacement use the 3 capture groups with a space between the group values.

    $1 $2 $3
    

    The output after the replacement:

    #include<stdio.h>
    a < b
    a<b>
    a < v and c > d
    

    In vim using the very magic mode \v

    :%s/\v\S@<!([^\s<>+])([<>])([^\s<>]+)\S@!/\1 \2 \3/g
    

    enter image description here