When using PCRE regex, is there a way to skip the first n occurences? I saw some examples with \K but I don't understand how to use it.
The goal is to find "px" values, so this is the regex I use:
(?!1px)(\d+)(px)
(?!1px) is used to ignore "1px".
Considering the following sample string, how could I skip the first (12px), or second (4px) match, to match only the third (2px)?
* {margin: 0; padding: 0; font-size: 12px; color: #555;}
.test {
display: inline-block;
border: 1px solid #000;
box-shadow: #aaa 4px 2px 6px;
width: 36px;
height: 24px;
}
You may use
(?s)^(?:.*?\b(?!1p)\d+px){2}.*?\K\b(?!1p)(\d+)(px)
See the regex demo
Details
(?s)
- DOTALL s
flag that makes .
match line break chars, too^
- start of a string(?:.*?\b(?!1p)\d+px){2}
- exactly two occurrences of any 0 or more chars, as few as possible, and then 1+ digits + px
but 1px
value.*?
- any 0+ chars, as few as possible\K
- match reset operator discarding the text matched so far\b
- word boundary(?!1p)
- no 1p
allowed immediately to the right(\d+)(px)
- 1+ digits captured in Group 1 and px
captured in Group 2.