Home > Enterprise >  How to build a regular expression with lookbehind correctly?
How to build a regular expression with lookbehind correctly?

Time:12-26

I tried to make a regular expression for replacing styles in WebStorm through the search and replacement line, but 5 hours of effort did not give anything.

(?<!vw\()(-?[0-9]*\.?[0-9] px)
padding: 25px 30px;
box-shadow: 0 vw(20px) vw(30px) rgba(10, 9, 3, 0.2);
border-radius: vw(20px);
margin-top: 10px;

The expectation is that all lines in which there are is a length in pixels (e.g. 20px) except those that are wrapped in vw() (e.g. vw(20px)) will be selected. That is, those lines that are emphasized in the image should not be selected

enter image description here

CodePudding user response:

It is not enough to exclude that the match is preceded with "vw(", as that might just mean a match can start one position later, after skipping a digit, and then of course the match is preceded by a digit, not a parenthesis.

To fix this, also require that the character that precedes the number is not a digit, nor a point, nor a minus sign, since that should then really be part of the matched number. You can do this with a second look-behind pattern: (?<![-.\d])

Not related to your question, but it leads to bad performance if you have an optional part (point) between two patterns that both match the same thing (a digit). To match a decimal number make the whole decimal part optional, not just the decimal point:

(?<!vw\()(?<![-.\d])(-?\d*(?:\.\d )?px)

See it on regex101

  • Related