简体   繁体   中英

How to build a regular expression with lookbehind correctly?

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 (eg 20px ) except those that are wrapped in vw() (eg vw(20px) ) will be selected. That is, those lines that are emphasized in the image should not be selected

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM