Home > Back-end >  Regex capture only 1 space except when surrounded by specific pattern
Regex capture only 1 space except when surrounded by specific pattern

Time:12-23

I'm having troubles writing a regex that captures one space but not when surrounded by hex characters and starting with a escaping \:

I should capture in these following lines :

.c ber
.cb ber
.test test
.\fc ker
.k ker

but not here :

.bob\fc ber
.\fc ber

Currently I came up with ((?<!(\\[\da-f][\da-f])) ) but this one does not handle the part where I need to capture the space not followed by a hex character.

I also tried (?<!\\[\da-f][\da-f]) (?![\da-f]) but this one does not match spaces that are followed by hex chars but are not preceded by hex chars.

Regex 101

CodePudding user response:

To let a lookahead only succeed if the negative lookbehind succeeds, it needs to be inside.

(?<!\\[a-f\d]{2}(?=.[a-f\d]))( )

See this demo at regex101

The lookbehind checks if not preceded by two hex characters and a backslash containing a lookahead to only disallow if one character after the next is a hex character.

  • Related