Home > Blockchain >  Regex distinguish < in logical operations and parenthesis pairs
Regex distinguish < in logical operations and parenthesis pairs

Time:11-08

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.

CodePudding user response:

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

enter image description here

  • Related